<?php
/**
 * 点大商城（www.diandashop.com） - 微信公众号小程序商城系统!
 * Copyright © 2020 山东点大网络科技有限公司 保留所有权利
 * =========================================================
 * 版本：V2
 * 授权主体：海南芒点网络科技有限公司
 * 授权域名：kf.hnmangdian.com
 * 授权码：iuGYepyTlKxWomKwhgsupaLmF
 * ----------------------------------------------
 * 您只能在商业授权范围内使用，不可二次转售、分发、分享、传播
 * 任何企业和个人不得对代码以任何目的任何形式的再发布
 * =========================================================
 */

namespace app\controller;
use think\facade\Db;
use think\facade\Log;

class ApiRestaurantShop extends ApiCommon{
    public function initialize(){
		parent::initialize();
        $bid = input('param.bid/d');
        //记录接口访问请求的bid
        if($bid > 0) cache($this->sessionid.'_api_bid',$bid,3600);
		if(getcustom('restaurant_shop_jingmo_auth')){
            $shop_is_jingmo = Db::name('restaurant_admin_set')->where('aid',aid)->value('shop_is_jingmo');
            if($shop_is_jingmo ==1 ){
                if(!$this->member){
                    $appinfo = \app\common\System::appinfo(aid,'h5');
                    return $this->json(['status'=>-1,'msg'=>'请先登录','authlogin'=>2,'ali_appid' => $appinfo['ali_appid']],1);   
                }
            }
        }
		$this->checklogin();
	}
	
	//点餐页面
	public function index(){
		$bid = input('param.bid/d', 0);
        $tableId = input('param.tableId/d', 0);
		if(!$bid) $bid = 0;
		if($bid!=0){
			$business = Db::name('business')->where('aid',aid)->where('id',$bid)->field('id,name,logo,content,pics,desc,tel,address,sales,start_hours,end_hours,zhengming,longitude,latitude')->find();
			$business['pic'] = explode(',',$business['pics'])[0];
            $business['zhengming'] = $business['zhengming'] ? explode(',',$business['zhengming']) : [];
		}else{
			$business = Db::name('admin_set')->where('aid',aid)->field('id,name,logo,desc,tel,address,longitude,latitude')->find();
		}
		$shop_set = Db::name('restaurant_shop_sysset')->where('aid',aid)->where('bid',$bid)->find();
		if(getcustom('restaurant_bar_table_order')){
		    $mdid = input('param.mdid');
		    if($tableId ==0 && $mdid){
                $tableId = 0;
                $shop_set['bar_table_order'] = 1;
            }
        }
		if($shop_set['banner']) $business['pic'] = $shop_set['banner'];

		if($shop_set['status']==0){
            return $this->json(['status'=>0,'msg'=>'该商家未开启点餐']);
		}
		if($shop_set['start_hours'] != $shop_set['end_hours']){
			$start_time = strtotime(date('Y-m-d '.$shop_set['start_hours']));
			$end_time = strtotime(date('Y-m-d '.$shop_set['end_hours']));
			if(($start_time < $end_time && ($start_time > time() || $end_time < time()))
                || ($start_time >= $end_time && ($start_time > time() && $end_time < time()))){
				return $this->json(['status'=>0,'msg'=>'该商家不在营业时间']);
			}
		}
        //系统设置
        $sysset = Db::name('admin_set')->field('name,logo,desc,tel,gzts,ddbb,ddbbtourl,mode,address')->where('aid',aid)->find();
        $shop_set['mode'] =$sysset['mode'];

        $shop_set['is_loc_business'] = 0;
        if(getcustom('loc_business')){
            $shop_set['is_loc_business'] = 1;
        }
        if(getcustom('restaurant_shop_takeaway_switch')){
            $shop_set['shop_takeaway_switch']= Db::name('restaurant_admin_set')->where('aid',aid)->value('shop_takeaway_switch');
        }
		$cid = input('param.cid');
		if(!$cid) $cid = 0;
		$clist = Db::name('restaurant_product_category')->where('aid',aid)->where('bid',$bid)->where('pid',$cid)->where('status',1)->where('is_shop',1)->order('sort desc,id')->select()->toArray();
		foreach($clist as $k=>$v){
			$where = [];
			$where[] = ['aid','=',aid];
            $where[] = ['bid','=',$bid]; 
			//$where[] = ['status','=',1];
			$where[] = ['ischecked','=',1];
//			$where[] = ['stock','>',0];
//			$where[] = Db::raw('stock_daily-sales_daily>0');
			$week = date("w");
			if($week==0) $week = 7;
			$where[] = Db::raw('find_in_set('.$week.',status_week)');
			$nowtime = time();
			$nowhm = date('H:i');
			$where[] = Db::raw("`status`=1 or (`status`=2 and unix_timestamp(start_time)<=$nowtime and unix_timestamp(end_time)>=$nowtime) or (`status`=3 and ((start_hours<end_hours and start_hours<='$nowhm' and end_hours>='$nowhm') or (start_hours>=end_hours and (start_hours<='$nowhm' or end_hours>='$nowhm'))) )");

			$where[] = Db::raw("find_in_set(".$v['id'].",cid)");
            //过滤单独购买菜品
            if(getcustom('restaurant_duli_buy')){
                $where[] = Db::raw("duli_buy = 0");
            }
            $field  ="pic,id,bid,name,stock,sales,market_price,sell_price,lvprice,lvprice_data,guigedata,limit_start,limit_per,stock_daily,sales_daily";
            if(getcustom('restaurant_weigh') || getcustom('restaurant_product_package')){
                $field .= ",product_type";
            }
            if(getcustom('restaurant_product_stock_daily')){
                $field .= ",total_stock_daily_real,total_stock_daily";
            }
            if(getcustom('restaurant_product_showtj')){
                $where2 = "find_in_set('-1',showtj)";
                if($this->member){
                    $where2 .= " or find_in_set('".$this->member['levelid']."',showtj)";
                    if($this->member['subscribe']==1){
                        $where2 .= " or find_in_set('0',showtj)";
                    }
                }
                $where[] = Db::raw($where2);
            }
            $prolist = Db::name('restaurant_product')->field($field)->where($where)->orderRaw('if(stock_daily>sales_daily,1,0) desc,sort desc,id desc')->select()->toArray();
            if(!$prolist) $prolist = [];
			$prolist = $this->formatprolist($prolist);
			if(!$prolist){
				unset($clist[$k]);
			}else{
				foreach($prolist as $k2=>$v2){
                    if(getcustom('member_level_price_show')){
                        //获取第一个规格的会员等级价格
                        $priceshows = [];
                        $price_show = 0;
                        $price_show_text = '';
                    }

					$gglist = Db::name('restaurant_product_guige')->where('product_id',$v2['id'])->select()->toArray();
                    foreach($gglist as $gk=>$gv){
                        if(getcustom('member_level_price_show')){
                            //获取第一个规格的会员等级价格
                            if($gk == 0 && $v2['lvprice'] == 1 && $gv['lvprice_data']){
                                $lvprice_data = json_decode($gv['lvprice_data'],true);
                                if($lvprice_data){
                                    $lk=0;
                                    foreach($lvprice_data as $lid=>$lv){
                                        $level = Db::name('member_level')->where('id',$lid)->where('price_show',1)->field('id,price_show_text')->find();
                                        if($level){
                                            //当前会员等级价格标记并去掉
                                            if($this->member && $this->member['levelid'] == $lid){
                                                $price_show = 1;
                                                $price_show_text = $level['price_show_text'];
                                            }else{
                                                $priceshow = [];
                                                $priceshow['id'] = $lid;
                                                $priceshow['sell_price'] = $lv;
                                                $priceshow['price_show_text'] = $level['price_show_text'];
                                                $priceshows[] = $priceshow;
                                            }
                                        }
                                        if($lk == 0){
                                            //普通价格
                                            $prolist[$k2]['sell_putongprice'] = $lv;
                                        }
                                        $lk ++ ;
                                    }
                                    unset($lid);unset($lv);
                                }
                            }
                        }
                    }
                    unset($gk);unset($gv);

                    if(getcustom('member_level_price_show')){
                        //获取第一个规格的会员等级价格
                        $prolist[$k2]['priceshows'] = $priceshows?$priceshows:'';
                        $prolist[$k2]['price_show'] = $price_show;
                        $prolist[$k2]['price_show_text'] = $price_show_text;
                    }

					$prolist[$k2]['gglist'] = $gglist;
					$prolist[$k2]['ggcount'] = count($gglist);
					if($v2['limit_start']==0) $v2['limit_start'] = 1;
					if($v2['limit_per']==0) $v2['limit_per'] = 999999;
					$have_jialiao = 0;
					if(getcustom('restaurant_product_jialiao')){
					     $jlcount = Db::name('restaurant_product_jialiao')->where('aid',aid)->where('bid',$v2['bid'])->where('proid',$v2['id'])->count();
					     if($jlcount){
                             $have_jialiao = 1;
                         }
                    }
                    $prolist[$k2]['have_jialiao'] =$have_jialiao;
					if(getcustom('restaurant_product_package')){
					    if($v2['product_type'] ==2){
                            $prolist[$k2]['stock_daily'] = 999999;
                            $prolist[$k2]['stock'] = 999999;
                        }
                    }
					if(getcustom('restaurant_product_stock_daily')){
					    if($v2['total_stock_daily'] > 0){
					        $sales_daily = $v2['total_stock_daily'] -$v2['total_stock_daily_real'] ;
                            $prolist[$k2]['sales_daily'] = $sales_daily<=0?0:$sales_daily;
                            $prolist[$k2]['stock_daily'] = $v2['total_stock_daily']; 
                        }
                    }
				}
				$clist[$k]['prolist'] = $prolist;
			}
		}
		$clist = array_values($clist);
		
		$cartwhere = [];
        $cartwhere[] = ['aid','=',aid];
        $cartwhere[] = ['bid','=',$bid];
        $is_use_mid =1;
        if(getcustom('restaurant_shop_pindan')){
            //先吃后付后续功能，以table为载体
            $bid = input('param.bid');
            $tableid = input('param.tableId');
            $table = Db::name('restaurant_table')->where('aid',aid)->where('id',$tableId)->find();
            if($table['pindan_status'] ==1){
                $is_use_mid = 0;
                $cartwhere[] = ['tableid','=',$tableid];
            }
        }
        if($is_use_mid)$cartwhere[] = ['mid','=',mid];
       
//        print_r($where);
		$list = Db::name('restaurant_shop_cart')->where($cartwhere)->order('createtime desc')->select()->toArray();
		$total = 0;
		$totalprice = 0;
		foreach($list as $k=>$v){
            $field ='cid,pic,aid,id,bid,name,stock,sales,market_price,sell_price,lvprice,lvprice_data,sellpoint,guigedata';
            if(getcustom('restaurant_weigh')){
                $field .= ",product_type";
            }
            $product = Db::name('restaurant_product')->field($field)->where('id',$v['proid'])->find();
			if(!$product){
				unset($list[$k]);
				Db::name('restaurant_shop_cart')->where('id',$v['id'])->delete();
				continue;
			}
			$product = $this->formatproduct($product);
			$guige = Db::name('restaurant_product_guige')->where('id',$v['ggid'])->find();

            $deletegg = 1;
            if(getcustom('restaurant_product_package')){
                if($v['package_data']){
                    $deletegg = 0;
                }
            }
			if(!$guige && $deletegg){
				unset($list[$k]);
				Db::name('restaurant_shop_cart')->where('id',$v['id'])->delete();
				continue;
			}
            $guige = $this->formatguige($guige,$product['bid'],$product['lvprice']);
            if (getcustom('restaurant_product_jialiao')){
                if($v['jldata']){
                    $jldata = json_decode($v['jldata'],true);
                    $njlprice = 0;
                    $njltitle = '';
                    foreach($jldata as $key=>$val){
                        $njlprice += $val['num'] * $val['price'];
                        $njltitle .=$val['title'].'*'.$val['num'].'/';
                    }
                    $guige['sell_price'] = dd_money_format($guige['sell_price'] + $njlprice) ;
                    $guige['name'] = $guige['name'].'('.rtrim($njltitle,'/').')';
                }
            }
		
			$total += $v['num'];
			$totalprice += $guige['sell_price'] * $v['num'];
			if(getcustom('product_jialiao')){
                $totalprice += $v['jlprice']* $v['num'];
            }
            $list[$k]['jltitle'] = isset($v['jltitle'])?$v['jltitle']:'';
            $list[$k]['jlprice'] = isset($v['jlprice'])?$v['jlprice']:0;
            if(getcustom('restaurant_product_package')){
                if($v['package_data']){
                    $package_data = json_decode($v['package_data'],true);
                    //拼接展示出已选套餐内容
                    $ggtext = [];
                    foreach($package_data as $key=>$pd){
                        $t = 'x'.$pd['num'].' '.$pd['proname'];
                        if($pd['ggname'] !='默认规格'){
                            $t .='('.$pd['ggname'].')'; 
                        }
                        $ggtext[] = $t; 
                    }
                    $list[$k]['ggtext'] =$ggtext;
                    //计算总价
                    $totalprice += dd_money_format($v['package_price'] * $v['num']);
                    //重置规格的数据，为了前台显示对应金额
                    $guige['sell_price'] = $v['package_price'];
                }
            }
            $list[$k]['product'] = $product;
            $list[$k]['guige'] = $guige;
		}
		$totalprice = number_format($totalprice,2,'.','');
		
		$cartList = ['list'=>$list,'total'=>$total,'totalprice'=>$totalprice];
		$numtotal = [];
		$numCat = [];
		foreach($clist as $i=>$v){
			foreach($v['prolist'] as $j=>$pro){
				$numtotal[$pro['id']] = 0;
                $numCat[$v['id']] = 0;
			}
		}
		foreach($cartList['list'] as $i=>$v){
			$numtotal[$v['proid']] += $v['num'];
            //分类数量
            if($v['product']['cid']) {
                $cids = explode(',', $v['product']['cid']);
                if($cids){
                    foreach ($cids as $cid)
                        $numCat[$cid] += $v['num'];
                }
            }
		}
		$table = [];
		$change_people_number = 0;//选择就餐人数
        $table = Db::name('restaurant_table')->where('aid',aid)->where('id',$tableId)->find();
        if($table){
            //显示商品名称
            $show_table_name = 1;
            $table['show_table_name'] = $show_table_name;
            //如果存在订单
            $order = Db::name('restaurant_shop_order')->where('aid',aid)->where('id', $table['orderid'])->find();
            
            if(!$order ||  $order['status'] != 0){
                $change_people_number = 1;
            } 
            if(getcustom('restaurant_shop_pindan')){
                 $shop_set['pay_after'] = $table['pindan_status'];//如果桌台有餐后付款，强制转换
            }
            //先付后吃，判断是否存在未结算的订单
            //桌台已有下单未支付时，自己的单跳转订单详情，其他人的单提示服务员处理
            if($order && $shop_set['pay_after'] ==0 && $order['status'] ==0 && $order['eattype']==0 && input('param.type') !='admin'){
                if(mid == $order['mid']){
                    return $this->json(['status'=>0,'msg' =>'已下单，去处理订单','url'=>'/restaurant/shop/orderdetail?id='.$order['id']]);
                }else{
                    return $this->json(['status'=>0,'msg' =>'该桌台已存在订单，请呼叫服务员']); 
                }
            }
        }
        $mdid = input('param.mdid');
		if(!$tableId && $mdid){
            $change_people_number = 1;
        }
		if(getcustom('restaurant_shop_select_renshu')){
		    //是否选择人数
            if($shop_set['select_renshu_status'] ==1){
                $change_people_number = 1;
            }else{
                $change_people_number = 0;
            }
        }
        $shop_set['change_people_number'] = $change_people_number;
        if(getcustom('restaurant_table_timing')){
            if($table){
                $table['timing_data1'] =   $table['timing_data1']?json_decode($table['timing_data1'],true):[];
                $table['timing_data2'] =   $table['timing_data2']?json_decode($table['timing_data2'],true):[];
            }
        }
        if(getcustom('restaurant_table_minprice')){
            if($shop_set['table_service_fee_type'] ==0){
                $tip = $table['service_fee_type'] ==0?$table['service_fee'].'元':floatval($table['service_fee']).'%';
                $table_minprice_tip = '请注意本桌台或包厢有'.$tip.'的服务费。若您消费（实际付款）达到'.$table['minprice'].'元，服务费免收。';
            }else{
                $table_minprice_tip = '本桌台或包厢消费有额外的服务费等费用产生，详情请查看屋内公示板或咨询服务员。';
            }
            $shop_set['table_minprice_tip'] = $table_minprice_tip;
        }
        if(getcustom('restaurant_shop_designer_page')){
            $designer_data = Db::name('restaurant_shop_designer_page')->where('aid',aid)->where('bid',$bid)->find();
            $pagecontent = json_decode(\app\common\System::initpagecontent($designer_data['content'],aid,mid,platform),true);
            $shop_set['designer_content'] = $pagecontent?$pagecontent:"";
        }
        if(getcustom('restaurant_takeaway_ad_images')){
            if($shop_set['ad_pics']){
                $shop_set['ad_pics_list'] = explode(',',$shop_set['ad_pics']);
            }else{
                $shop_set['ad_pics_list'] =[];
            }
            if($shop_set['ad_pics2']){
                $shop_set['ad_pics_list2'] = explode(',',$shop_set['ad_pics2']);
            }else{
                $shop_set['ad_pics_list2'] =[];
            }
        }
        if(getcustom('restaurant_shop_takeaway_switch')){
            $mendian = Db::name('mendian')->where('aid',aid)->where('bid',$bid)->where('status',1)->order('id asc')->find();
            $business['mdid'] =  $mendian['id'];
            $business['bid'] =  $bid;
        }
        $order =[];
        if($table['orderid']){
            $order =  Db::name('restaurant_shop_order')->where('aid',aid)->where('id',$table['orderid'])->field('id,bid,renshu,tableid')->find();
            $goodsnum = Db::name('restaurant_shop_order_goods')->where('aid',aid)->where('orderid',$table['orderid'])->count();
            $order['goodsnum'] = $goodsnum??0;
        }
		$rdata = [];
		$rdata['status'] = 1;
		$rdata['data'] = $clist;
		$rdata['cartList'] = $cartList;
		$rdata['numtotal'] = $numtotal;
        $rdata['numCat'] = $numCat;
		$rdata['business'] = $business;
		$rdata['sysset'] = $shop_set;
        $rdata['table'] = $table;
        $rdata['order'] = $order;
        if(getcustom('restaurant_bar_table_order')){
             $mdid = input('param.mdid');
            $mdinfo = Db::name('mendian')->where('id',$mdid)->field('id,name,address,longitude,latitude,province,city,district,tel')->find();
            $rdata['mdinfo'] = $mdinfo;
        }
        if(getcustom('restaurant_shop_pindan')){
            $config = include(ROOT_PATH.'config.php');
            $authtoken = $config['authtoken'];
            $rdata['token'] = md5(md5($authtoken.aid.$bid.$table['id']));
        }
		return $this->json($rdata);
	}
	//菜品列表
    public function getprolist(){
        $where = [];
        $where[] = ['aid','=',aid];
        $where[] = ['ischecked','=',1];
        //$where[] = ['status','=',1];
        $week = date("w");
        if($week==0) $week = 7;
        $where[] = Db::raw('find_in_set('.$week.',status_week)');
        $nowtime = time();
        $nowhm = date('H:i');
        $where[] = Db::raw("`status`=1 or (`status`=2 and unix_timestamp(start_time)<=$nowtime and unix_timestamp(end_time)>=$nowtime) or (`status`=3 and ((start_hours<end_hours and start_hours<='$nowhm' and end_hours>='$nowhm') or (start_hours>=end_hours and (start_hours<='$nowhm' or end_hours>='$nowhm'))) )");

        if(input('param.bid')){
            $bid = input('param.bid/d');
            $where[] = ['bid','=',input('param.bid/d')];
        }else{
            $business_sysset = Db::name('business_sysset')->where('aid',aid)->find();
            if(!$business_sysset || $business_sysset['status']==0 || $business_sysset['product_isshow']==0){
                $where[] = ['bid','=',0];
            }
            $bid = 0;
        }

        if(input('param.field') && input('param.order')){
            $order = input('param.field').' '.input('param.order').',sort desc,id desc';
        }else{
            $order = 'sort desc,id desc';
        }
        //分类
        if(input('param.cid')){
            $cid = input('post.cid') ? input('post.cid/d') : input('param.cid/d');
            //子分类
            $clist = Db::name('restaurant_product_category')->where('aid',aid)->where('bid',$bid)->where('pid',$cid)->column('id');
            if($clist){
                $clist2 = Db::name('restaurant_product_category')->where('aid',aid)->where('bid',$bid)->where('pid','in',$clist)->column('id');
                $cCate = array_merge($clist, $clist2, [$cid]);
                if($cCate){
                    $whereCid = [];
                    foreach($cCate as $k => $c2){
                        $whereCid[] = "find_in_set({$c2},cid)";
                    }
                    $where[] = Db::raw(implode(' or ',$whereCid));
                }
            } else {
                $where[] = Db::raw("find_in_set(".$cid.",cid)");
            }
        } else {
            $clist = Db::name('restaurant_product_category')->where('aid',aid)->where('bid',$bid)->where('status',1)->where('is_shop',1)->order('sort desc,id')->select()->toArray();
            $cidwhere = '';
            foreach($clist as $k=>$v){
                if($k == count($clist)-1){
                    $cidwhere .= "find_in_set(".$v['id'].",cid)";
                } else
                $cidwhere .= " find_in_set(".$v['id'].",cid) or ";
            }
            $where[] = Db::raw($cidwhere);
        }

        if(input('param.keyword')){
            $where[] = ['name','like','%'.input('param.keyword').'%'];
        } else {
            return $this->json(['status'=>1,'data'=>[]]);
        }

        $pernum = 10;
        $pagenum = input('post.pagenum');
        if(!$pagenum) $pagenum = 1;
//        $datalist = Db::name('restaurant_product')->field("id,pic,name,sales,market_price,sell_price,lvprice,lvprice_data,sellpoint")->where($where)->page($pagenum,$pernum)->order($order)->select()->toArray();
        $field = "pic,id,name,stock,sales,market_price,sell_price,lvprice,lvprice_data,guigedata,limit_start,limit_per,stock_daily,sales_daily";
        if(getcustom('restaurant_weigh')){
            $field .= ",product_type";
        }
        if(getcustom('restaurant_product_showtj')){
            $where2 = "find_in_set('-1',showtj)";
            if($this->member){
                $where2 .= " or find_in_set('".$this->member['levelid']."',showtj)";
                if($this->member['subscribe']==1){
                    $where2 .= " or find_in_set('0',showtj)";
                }
            }
            $where[] = Db::raw($where2);
        }
        $prolist = Db::name('restaurant_product')->field($field)->where($where)->page($pagenum,$pernum)->orderRaw('if(stock_daily>sales_daily,1,0) desc,'.$order)->select()->toArray();
        if(!$prolist) $prolist = [];
        $prolist = $this->formatprolist($prolist);
        if(!$prolist){
            unset($clist[$k]);
        }else{
            foreach($prolist as $k2=>$v2){
                if(getcustom('member_level_price_show')){
                    //获取第一个规格的会员等级价格
                    $priceshows = [];
                    $price_show = 0;
                    $price_show_text = '';
                }
                $gglist = Db::name('restaurant_product_guige')->where('product_id',$v2['id'])->select()->toArray();
                foreach($gglist as $gk=>$gv){
                    if(getcustom('member_level_price_show')){
                        //获取第一个规格的会员等级价格
                        if($gk == 0 && $v2['lvprice'] == 1 && $gv['lvprice_data']){
                            $lvprice_data = json_decode($gv['lvprice_data'],true);
                            if($lvprice_data){
                                $lk=0;
                                foreach($lvprice_data as $lid=>$lv){
                                    $level = Db::name('member_level')->where('id',$lid)->where('price_show',1)->field('id,price_show_text')->find();
                                    if($level){
                                        //当前会员等级价格标记并去掉
                                        if($this->member && $this->member['levelid'] == $lid){
                                            $price_show = 1;
                                            $price_show_text = $level['price_show_text'];
                                        }else{
                                            $priceshow = [];
                                            $priceshow['id'] = $lid;
                                            $priceshow['sell_price'] = $lv;
                                            $priceshow['price_show_text'] = $level['price_show_text'];
                                            $priceshows[] = $priceshow;
                                        }
                                    }
                                    if($lk == 0){
                                        //普通价格
                                        $prolist[$k2]['sell_putongprice'] = $lv;
                                    }
                                    $lk ++ ;
                                }
                                unset($lid);unset($lv);
                            }
                        }
                    }
                }
                unset($gk);unset($gv);

                if(getcustom('member_level_price_show')){
                    //获取第一个规格的会员等级价格
                    $prolist[$k2]['priceshows'] = $priceshows?$priceshows:'';
                    $prolist[$k2]['price_show'] = $price_show;
                    $prolist[$k2]['price_show_text'] = $price_show_text;
                }
                $prolist[$k2]['gglist'] = $gglist;
                $prolist[$k2]['ggcount'] = count($gglist);
                if($v2['limit_start']==0) $v2['limit_start'] = 1;
                if($v2['limit_per']==0) $v2['limit_per'] = 999999;
            }
            $clist[$k]['prolist'] = $prolist;
        }
        if(!$prolist) $prolist = [];
//        $datalist = $this->formatprolist($datalist);
        return $this->json(['status'=>1,'data'=>$prolist]);
    }
	//获取菜品列表 评价列表
	public function getdatalist(){
		$id = input('param.id/d');
		$st = input('param.st/d');
		$pagenum = input('param.pagenum');
		if(!$pagenum) $pagenum = 1;
		if($st == 0){//菜品
			$pernum = 20;
			$where = [];
			$where[] = ['aid','=',aid];
			$where[] = ['bid','=',$id];
			//$where[] = ['status','=',1];
			$nowtime = time();
			$nowhm = date('H:i');
			$where[] = Db::raw("`status`=1 or (`status`=2 and unix_timestamp(start_time)<=$nowtime and unix_timestamp(end_time)>=$nowtime) or (`status`=3 and ((start_hours<end_hours and start_hours<='$nowhm' and end_hours>='$nowhm') or (start_hours>=end_hours and (start_hours<='$nowhm' or end_hours>='$nowhm'))) )");

			$prolist = Db::name('restaurant_product')->where($where)->page($pagenum,$pernum)->order('id desc')->select()->toArray();
			if(!$prolist) $prolist = [];
			if(request()->isPost()){
				return $this->json(['status'=>1,'data'=>$prolist]);
			}
		}else{//评价
			$pernum = 10;
			$where = [];
			$where[] = ['aid','=',aid];
			$where[] = ['bid','=',$id];
			$where[] = ['status','=',1];
			$commentlist = Db::name('business_comment')->where($where)->page($pagenum,$pernum)->order('id desc')->select()->toArray();
			if(!$commentlist) $commentlist = [];
			foreach($commentlist as $k=>$pl){
				$commentlist[$k]['createtime'] = date('Y-m-d H:i',$pl['createtime']);
				if($commentlist[$k]['content_pic']) $commentlist[$k]['content_pic'] = explode(',',$commentlist[$k]['content_pic']);
			}
			if(request()->isPost()){
				return $this->json(['status'=>1,'data'=>$commentlist]);
			}
		}
	}

	//菜品
	public function product(){
		$proid = input('param.id/d');
		$product = Db::name('restaurant_product')->where('id',$proid)->where('aid',aid)->find();
		if(!$product) return $this->json(['status'=>0,'msg'=>'菜品不存在']);
		if($product['status']==0) return $this->json(['status'=>0,'msg'=>'菜品未上架']);
		if($product['ischecked']!=1) return $this->json(['status'=>0,'msg'=>'菜品未审核']);
		
		if($product['status']==2 && (strtotime($product['start_time']) > time() || strtotime($product['end_time']) < time())){
			return $this->json(['status'=>0,'msg'=>'菜品未上架']);
		}
		if($product['status']==3){
			$start_time = strtotime(date('Y-m-d '.$product['start_hours']));
			$end_time = strtotime(date('Y-m-d '.$product['end_hours']));
			if(($start_time < $end_time && ($start_time > time() || $end_time < time())) || ($start_time >= $end_time && ($start_time > time() && $end_time < time()))){
				return $this->json(['status'=>0,'msg'=>'菜品未上架']);
			}
		}
		if($product['status']==2 || $product['status']==3) $product['status']=1;

		if(!$product['pics']) $product['pics'] = $product['pic'];
		$product['pics'] = explode(',',$product['pics']);
		$product = $this->formatproduct($product);

        if(getcustom('member_level_price_show')){
            //获取第一个规格的会员等级价格
            $priceshows = [];
            $price_show = 0;
            $price_show_text = '';
        }
        $gglist = Db::name('restaurant_product_guige')->where('product_id',$product['id'])->select()->toArray();
        foreach($gglist as $k=>$v){
            if(getcustom('member_level_price_show')){
                //获取第一个规格的会员等级价格
                if($k == 0 && $product['lvprice'] == 1 && $v['lvprice_data']){
                    $lvprice_data = json_decode($v['lvprice_data'],true);
                    if($lvprice_data){
                        $lk=0;
                        foreach($lvprice_data as $lid=>$lv){
                            $level = Db::name('member_level')->where('id',$lid)->where('price_show',1)->field('id,price_show_text')->find();
                            if($level){
                                //当前会员等级价格标记并去掉
                                if($this->member && $this->member['levelid'] == $lid){
                                    $price_show = 1;
                                    $price_show_text = $level['price_show_text'];
                                }else{
                                    $priceshow = [];
                                    $priceshow['id'] = $lid;
                                    $priceshow['sell_price'] = $lv;
                                    $priceshow['price_show_text'] = $level['price_show_text'];
                                    $priceshows[] = $priceshow;
                                }
                            }
                            if($lk == 0){
                                //普通价格
                                $product['sell_putongprice'] = $lv;
                            }
                            $lk ++ ;
                        }
                        unset($lid);unset($lv);
                    }
                    
                }
            }
        }
        if(getcustom('member_level_price_show')){
            //获取第一个规格的会员等级价格
            $product['priceshows'] = $priceshows?$priceshows:'';
            $product['price_show'] = $price_show;
            $product['price_show_text'] = $price_show_text;
        }

		//是否收藏
		$rs = Db::name('member_favorite')->where('aid',aid)->where('mid',mid)->where('proid',$proid)->where('type','restaurant')->find();
		if($rs){
			$isfavorite = true;
		}else{
			$isfavorite = false;
		}
		//获取评论
		$commentlist = Db::name('restaurant_shop_comment')->where('aid',aid)->where('proid',$proid)->where('status',1)->order('id desc')->limit(10)->select()->toArray();
		if(!$commentlist) $commentlist = [];
		foreach($commentlist as $k=>$pl){
			$commentlist[$k]['createtime'] = date('Y-m-d H:i',$pl['createtime']);
			if($commentlist[$k]['content_pic']) $commentlist[$k]['content_pic'] = explode(',',$commentlist[$k]['content_pic']);
		}
		$commentcount = Db::name('restaurant_shop_comment')->where('aid',aid)->where('proid',$proid)->where('status',1)->count();
		//添加浏览历史
		if(mid){
			$rs = Db::name('member_history')->where('aid',aid)->where('mid',mid)->where('proid',$proid)->where('type','restaurant_shop')->find();
			if($rs){
				Db::name('member_history')->where('id',$rs['id'])->update(['createtime'=>time()]);
			}else{
				Db::name('member_history')->insert(['aid'=>aid,'mid'=>mid,'proid'=>$proid,'type'=>'restaurant_shop','createtime'=>time()]);
			}
		}

		$shopset = Db::name('restaurant_admin_set')->where('aid',aid)->field('shop_comment,shop_showcommission showcommission')->find();
        $sysset = Db::name('admin_set')->where('aid',aid)->field('name,logo,desc,fxjiesuantype,tel,kfurl,gzts,ddbb')->find();

        //预计佣金
        $commission = 0;
        $product['commission_desc'] = '元';
        if($this->member && $shopset['showcommission']==1 && $product['commissionset']!=-1){
            $userlevel = Db::name('member_level')->where('aid',aid)->where('id',$this->member['levelid'])->find();
            if($userlevel['can_agent']!=0){
                if($product['commissionset']==1){//按比例
                    $commissiondata = json_decode($product['commissiondata1'],true);
                    if($commissiondata){
                        $commission = $commissiondata[$userlevel['id']]['commission1'] * ($product['sell_price'] - ($sysset['fxjiesuantype']==2 ? $product['cost_price'] : 0)) * 0.01;
                    }
                }elseif($product['commissionset']==2){//按固定金额
                    $commissiondata = json_decode($product['commissiondata2'],true);
                    if($commissiondata){
                        $commission = $commissiondata[$userlevel['id']]['commission1'];
                    }
                }elseif($product['commissionset']==3) {//提成是积分
                    $commissiondata = json_decode($product['commissiondata3'],true);
                    if($commissiondata){
                        $commission = $commissiondata[$userlevel['id']]['commission1'];
                    }
                    $product['commission_desc'] = t('积分');
                }elseif($product['commissionset']==0){//按会员等级
                    if($userlevel['commissiontype']==1){ //固定金额按单
                        $commission = $userlevel['commission1'];
                    }else{
                        $commission = $userlevel['commission1'] * ($product['sell_price'] - ($sysset['fxjiesuantype']==2 ? $product['cost_price'] : 0)) * 0.01;
                    }
                }
            }
        }
		$product['commission'] = round($commission*100)/100;
		unset($product['cost_price']);

		if($product['bid']!=0){
			$business = Db::name('business')->where('aid',aid)->where('id',$product['bid'])->field('id,name,logo,desc,tel,address,sales,kfurl')->find();
		}else{
			$business = $sysset;
		}
		$product['detail'] = \app\common\System::initpagecontent($product['detail'],aid,mid,platform);
		$product['comment_starnum'] = floor($product['comment_score']);
		
		//促销活动
		$cuxiaolist = Db::name('restaurant_cuxiao')
			->where('aid',aid)
			->where('bid',$product['bid'])
			->where('starttime','<',time())
			->where('endtime','>',time())
			->order('sort desc')->select()->toArray();
		$newcxlist = [];
		foreach($cuxiaolist as $k=>$v){
			$gettj = explode(',',$v['gettj']);
			if(!in_array('-1',$gettj) && !in_array($this->member['levelid'],$gettj)){ //不是所有人
				continue;
			}
            if(getcustom('restaurant_cuxiao_activity_day')){
                //促销活动日
                if($v['activity_day_type'] ==0){//周几
                    $now_week = date('w');
                    $activity_day_week = explode(',',$v['activity_day_week']);
                    if(!in_array($now_week,$activity_day_week)){
                        continue;
                    }
                }else{//几号
                    $now_date = date('d');
                    $activity_day_date = explode(',',$v['activity_day_week']);
                    if(!in_array($now_date,$activity_day_date)){
                        continue;
                    }
                }
            }
            if(getcustom('restaurant_cuxiao_use_time_range')){
                $now_time =strtotime(date('H:i:s'));
                if($v['use_starttime'] && $v['use_endtime'] && ( $now_time < strtotime($v['use_starttime']) || $now_time > strtotime($v['use_endtime']))){
                    continue;
                }
            }
            //多时间段
            if(getcustom('restaurant_cuxiao_multi_use_time_range')){
                $multi_time_range = json_decode($v['multi_time_range'],true);
                if($multi_time_range){
                    $now_time =strtotime(date('H:i'));
                    $is_rangetime = 0;
                    foreach($multi_time_range as $rangetime){
                        if($now_time > strtotime($rangetime['starttime'])  && $now_time < strtotime($rangetime['endtime'])){
                            $is_rangetime =1;
                        }
                    }
                    if(!$is_rangetime)continue;
                }
            }
			if($v['fwtype']==2){//指定菜品可用
				$productids = explode(',',$v['productids']);
				if(!in_array($product['id'],$productids)){
					continue;
				}
			}
			if($v['fwtype']==1){//指定类目可用
				$categoryids = explode(',',$v['categoryids']);
				$cids = explode(',',$product['cid']);
				$clist = Db::name('restaurant_product_category')->where('pid','in',$categoryids)->select()->toArray();
				foreach($clist as $kc=>$vc){
					$categoryids[] = $vc['id'];
					$cate2 = Db::name('restaurant_product_category')->where('pid',$vc['id'])->find();
					$categoryids[] = $cate2['id'];
				}
				if(!array_intersect($cids,$categoryids)){
					continue;
				}
			}
			$newcxlist[] = $v;
		}
		//优惠券
		$couponlist = Db::name('coupon')->where('aid',aid)->where('bid',$product['bid'])->where('tolist',1)->where('type','5')->where("unix_timestamp(starttime)<=".time()." and unix_timestamp(endtime)>=".time())->order('sort desc')->select()->toArray();
		$newcplist = [];
		foreach($couponlist as $k=>$v){
			$gettj = explode(',',$v['gettj']);
			if(!in_array('-1',$gettj) && !in_array($this->member['levelid'],$gettj)){ //不是所有人
				continue;
			}
			if($v['fwtype']==2){//指定菜品可用
				$productids = explode(',',$v['productids']);
				if(!in_array($product['id'],$productids)){
					continue;
				}
			}
			if($v['fwtype']==1){//指定类目可用
				$categoryids = explode(',',$v['categoryids']);
				$cids = explode(',',$product['cid']);
				$clist = Db::name('restaurant_product_category')->where('id','in',$cids)->select()->toArray();
				foreach($clist as $kc=>$vc){
					if($vc['pid']){
						$cids[] = $vc['pid'];
						$cate2 = Db::name('restaurant_product_category')->where('id',$vc['pid'])->find();
						if($cate2 && $cate2['pid']){
							$cids[] = $cate2['pid'];
						}
					}
				}
				if(!array_intersect($cids,$categoryids)){
					continue;
				}
			}
			$haveget = Db::name('coupon_record')->where('aid',aid)->where('mid',mid)->where('couponid',$v['id'])->count();
			$v['haveget'] = $haveget;
			$v['starttime'] = date('m-d H:i',strtotime($v['starttime']));
			$v['endtime'] = date('m-d H:i',strtotime($v['endtime']));
			if($v['yxqtype'] == 1){
				$yxqtime = explode(' ~ ',$v['yxqtime']);
				$v['yxqdate'] = strtotime($yxqtime[1]);
            }elseif($v['yxqtype'] == 2){
				$v['yxqdate'] = time() + 86400 * $v['yxqdate'];
            }elseif($v['yxqtype'] == 3) {
                //次日起计算有效期
                $v['yxqdate'] = strtotime(date('Y-m-d')) + 86400 * ($v['yxqdate'] + 1) - 1;
            }
            if($v['bid'] > 0){
                $v['bname'] = Db::name('business')->where('aid',aid)->where('id',$v['bid'])->value('name');
            }
			$newcplist[] = $v;
		}

		$rdata = [];
		$rdata['status'] = 1;
		$rdata['title'] = $product['name'];
		$rdata['shopset'] = $shopset;
		$rdata['isfavorite'] = $isfavorite;
		$rdata['product'] = $product;
		$rdata['business'] = $business;
		$rdata['commentlist'] = $commentlist;
		$rdata['commentcount'] = $commentcount;
		$rdata['cartnum'] = Db::name('restaurant_shop_cart')->where('aid',aid)->where('mid',mid)->sum('num');
		$rdata['cuxiaolist'] = $newcxlist;
		$rdata['couponlist'] = $newcplist;
		return $this->json($rdata);
	}
	//获取菜品详情
	public function getproductdetail(){
		$proid = input('param.id/d');
		$where = [];
		$where[] = ['aid','=',aid];
		$where[] = ['id','=',$proid];
        $field = "id,pic,name,sales,market_price,sell_price,lvprice,lvprice_data,guigedata,status,ischecked,freighttype,start_time,end_time,start_hours,end_hours,commissionset,commissiondata1,commissiondata2,commissiondata3,sellpoint,status_week";
        if(getcustom('product_jialiao')){
            $field = $field.',jialiaodata';    
        }
        if(getcustom('restaurant_product_jialiao')){
            $field = $field.',jl_total_limit,jl_is_selected';
        }
		$product = Db::name('restaurant_product')->field($field)->where($where)->find();
		if(!$product){
			return $this->json(['status'=>0,'msg'=>'菜品不存在']);
		}
        //判断星期几
        $week = date('w');
        if($week ==0)$week = 7;
        $status_week = explode(',',$product['status_week']);
        if(!in_array($week,$status_week)){
            return $this->json(['status'=>0,'msg'=>'今日不可点']);
        }
		$product = $this->formatproduct($product);
		if($product['status']==0) return $this->json(['status'=>0,'msg'=>'菜品已下架']);
		if($product['ischecked']!=1) return $this->json(['status'=>0,'msg'=>'菜品未审核']);
		if($product['status']==2 && (strtotime($product['start_time']) > time() || strtotime($product['end_time']) < time())){
			return $this->json(['status'=>0,'msg'=>'菜品未上架']);
		}
		if($product['status']==3){
			$start_time = strtotime(date('Y-m-d '.$product['start_hours']));
			$end_time = strtotime(date('Y-m-d '.$product['end_hours']));
			if(($start_time < $end_time && ($start_time > time() || $end_time < time())) || ($start_time >= $end_time && ($start_time > time() && $end_time < time()))){
				return $this->json(['status'=>0,'msg'=>'菜品未上架']);
			}
		}
		if($product['status']==2 || $product['status']==3) $product['status']=1;

		$gglist = Db::name('restaurant_product_guige')->where('product_id',$product['id'])->select()->toArray();
		$gglist = $this->formatgglist($gglist,$product['bid'],$product['lvprice']);

        $sysset = Db::name('admin_set')->where('aid',aid)->field('name,logo,desc,fxjiesuantype,tel,kfurl,gzts,ddbb')->find();
        $shopset = Db::name('shop_sysset')->where('aid',aid)->field('showjd,comment,showcommission,hide_sales')->find();

        $guigelist = array();
        $not_selected = [];
		foreach($gglist as $k=>$v){
            //预计佣金
            $commission = 0;
            $v['commission_desc'] = '元';
            //计算佣金
            if($this->member && $shopset['showcommission']==1 && $product['commissionset']!=-1){
                $userlevel = Db::name('member_level')->where('aid',aid)->where('id',$this->member['levelid'])->find();
                if($userlevel['can_agent']!=0){
                    if($product['commissionset']==1){//按比例
                        $commissiondata = json_decode($product['commissiondata1'],true);
                        if($commissiondata){
                            $commission = $commissiondata[$userlevel['id']]['commission1'] * ($v['sell_price'] - ($sysset['fxjiesuantype']==2 ? $v['cost_price'] : 0)) * 0.01;
                        }
                    }elseif($product['commissionset']==2){//按固定金额
                        $commissiondata = json_decode($product['commissiondata2'],true);
                        if($commissiondata){
                            $commission = $commissiondata[$userlevel['id']]['commission1'];
                        }
                    }elseif($product['commissionset']==3) {//提成是积分
                        $commissiondata = json_decode($product['commissiondata3'],true);
                        if($commissiondata){
                            $commission = $commissiondata[$userlevel['id']]['commission1'];
                        }
                        $v['commission_desc'] = t('积分');
                    }elseif($product['commissionset']==4 && $product['lvprice']==1){//按价格差
                        $lvprice_data = json_decode($v['lvprice_data'],true);
                        $commission = array_shift($lvprice_data) - $v['sell_price'];
                        if($commission < 0) $commission = 0;
                    }elseif($product['commissionset']==0){//按会员等级
                        //fxjiesuantype 0按菜品价格,1按成交价格,2按销售利润
                        if($userlevel['commissiontype']==1){ //固定金额按单
                            $commission = $userlevel['commission1'];
                        }else{
                            $commission = $userlevel['commission1'] * ($v['sell_price'] - ($sysset['fxjiesuantype']==2 ? $v['cost_price'] : 0)) * 0.01;
                        }
                    }
                }
            }
            $v['commission'] = round($commission*100)/100;
            if(getcustom('restaurant_product_guige_hide')){
                if($v['show_status'] ==1){
                    $not_selected[] = $v['ks'];
                }
            }
			$guigelist[$v['ks']] = $v;
		}
		$guigedata = json_decode($product['guigedata'],true);
	
		$ggselected = [];
		foreach($guigedata as $v) {
			$ggselected[] = 0;
		}
		$ks = implode(',',$ggselected);
        $jialiaodata = [];
        if(getcustom('product_jialiao')){
            if(!empty($product['jialiaodata'])){
                $jialiaodata = json_decode($product['jialiaodata'],true);
            }
        }
        //新加料
        $jldata = [];
        if(getcustom('restaurant_product_jialiao')){
            $productjialiao = Db::name('restaurant_product_jialiao')->where('proid',$product['id'])->select()->toArray();
            foreach($productjialiao as $key=>$val){
                $jldata[] = ['id' => $val['id'],'title' => $val['title'],'limit_num'=>$val['limit_num'],'num' => 0,'price' => $val['price']];
            }
        }
		return $this->json(['status'=>1,'product'=>$product,'guigelist'=>$guigelist,'guigedata'=>$guigedata,'ggselected'=>$ggselected,'ks'=>$ks,'shopset' => $shopset,'jialiaodata' =>$jialiaodata,'jldata' =>$jldata,'not_selected' => $not_selected]);
	}
	//菜品评价
	public function commentlist(){
		$proid = input('param.proid/d');
		$pagenum = input('post.pagenum');
		if(!$pagenum) $pagenum = 1;
		$pernum = 20;
		$where = [];
		$where[] = ['aid','=',aid];
		$where[] = ['proid','=',$proid];
		$where[] = ['status','=',1];
		$datalist = Db::name('restaurant_shop_comment')->where($where)->page($pagenum,$pernum)->order('id desc')->select()->toArray();
		if(!$datalist) $datalist = [];
		foreach($datalist as $k=>$pl){
			$datalist[$k]['createtime'] = date('Y-m-d H:i',$pl['createtime']);
			if($datalist[$k]['content_pic']) $datalist[$k]['content_pic'] = explode(',',$datalist[$k]['content_pic']);
		}
		if(request()->isPost()){
			return $this->json(['status'=>1,'data'=>$datalist]);
		}
		$rdata = [];
		$rdata['datalist'] = $datalist;
		return $this->json($rdata);
	}
	//菜品海报
	function getposter(){
		$this->checklogin();
		$post = input('post.');
		$platform = platform;
		$page = '/restaurant/shop/product';
		$scene = 'id_'.$post['proid'].'-pid_'.$this->member['id'];
		//if($platform == 'mp' || $platform == 'h5' || $platform == 'app'){
		//	$page = PRE_URL .'/h5/'.aid.'.html#'. $page;
		//}
		$posterset = Db::name('admin_set_poster')->where('aid',aid)->where('type','product')->where('platform',$platform)->order('id')->find();

//		$posterdata = Db::name('member_poster')->where('aid',aid)->where('mid',mid)->where('scene',$scene)->where('type','restaurant_shop')->where('posterid',$posterset['id'])->find();
		if(true || !$posterdata){
			$product = Db::name('restaurant_product')->where('id',$post['proid'])->find();
			$product = $this->formatproduct($product);
			$sysset = Db::name('admin_set')->where('aid',aid)->find();
			$textReplaceArr = [
				'[头像]'=>$this->member['headimg'],
				'[昵称]'=>$this->member['nickname'],
				'[姓名]'=>$this->member['realname'],
				'[手机号]'=>$this->member['mobile'],
				'[商城名称]'=>$sysset['name'],
				'[商品名称]'=>$product['name'],
				'[商品销售价]'=>$product['sell_price'],
				'[商品市场价]'=>$product['market_price'],
				'[商品图片]'=>$product['pic'],
			];

			$poster = $this->_getposter(aid,$product['bid'],$platform,$posterset['content'],$page,$scene,$textReplaceArr);
			$posterdata = [];
			$posterdata['aid'] = aid;
			$posterdata['mid'] = $this->member['id'];
			$posterdata['scene'] = $scene;
			$posterdata['page'] = $page;
			$posterdata['type'] = 'product';
			$posterdata['poster'] = $poster;
            $posterdata['posterid'] = $posterset['id'];
			$posterdata['createtime'] = time();
//			Db::name('member_poster')->insert($posterdata);
		}
		return $this->json(['status'=>1,'poster'=>$posterdata['poster']]);
	}
	//购物车 
	public function cart(){
		//$this->checklogin();
        $gwcdata = [];
        $where = [];
        $where[] = ['aid','=',aid];
        $is_user_mid = 1;
        if(getcustom('restaurant_shop_pindan')){
            //先吃后付后续功能，以table为载体
            $bid = input('param.bid');
            $tableid = input('param.tableId');
            if($tableid > 0){
                $is_user_mid = 0;
                $where[] = ['tableid','=',$tableid];
            }
        }
        if($is_user_mid)$where[] = ['mid','=',mid];

        $cartlist = Db::name('restaurant_shop_cart')->field('id,bid,proid,ggid,num')->where($where)->order('createtime desc')->select()->toArray();
        if(!$cartlist) $cartlist = [];
        $newcartlist = [];
        foreach($cartlist as $k=>$gwc){
            if($newcartlist[$gwc['bid']]){
                $newcartlist[$gwc['bid']][] = $gwc;
            }else{
                $newcartlist[$gwc['bid']] = [$gwc];
            }
        }
		foreach($newcartlist as $bid=>$gwclist){
			if($bid == 0){
				$business = Db::name('admin_set')->where('aid',aid)->field('id,name,logo,tel')->find();
			}else{
				$business = Db::name('business')->where('aid',aid)->where('id',$bid)->field('id,name,logo,tel')->find();
			}
			$prolist = [];
			foreach($gwclist as $gwc){
				$product = Db::name('restaurant_product')->where('aid',aid)->where('status','<>',0)->where('id',$gwc['proid'])->find();
				if(!$product){
					Db::name('restaurant_shop_cart')->where('aid',aid)->where('proid',$gwc['proid'])->delete();continue;
				}
				$guige = Db::name('restaurant_product_guige')->where('id',$gwc['ggid'])->find();
				if(!$guige){
					Db::name('restaurant_shop_cart')->where('aid',aid)->where('ggid',$gwc['ggid'])->delete();continue;
				}
                $guige = $this->formatguige($guige,$product['bid'],$product['lvprice']);
				$prolist[] = ['id'=>$gwc['id'],'checked'=>true,'product'=>$product,'guige'=>$guige,'num'=>$gwc['num']];
			}
			$newcartlist[$bid] = ['bid'=>$bid,'checked'=>true,'business'=>$business,'prolist'=>$prolist];
		}
		
		$rdata = [];
		$rdata['cartlist'] = array_values($newcartlist);
		$rdata['tjdatalist'] = [];
		return $this->json($rdata);
	}
	public function addcart(){
		$this->checklogin();
		$post = input('post.');
		$oldnum = 0;
		$num = intval($post['num']);
		if(getcustom('restaurant_product_package')){
            $package_data = input('param.package_data');
        }
		$product = Db::name('restaurant_product')->where('aid',aid)->where('status','<>',0)->where('ischecked',1)->where('id',$post['proid'])->find();
		if(!$product) return $this->json(['status'=>0,'msg'=>'产品不存在或已下架']);
        //周几可点
        $week = date("w");
        if($week==0) $week = 7;
        $status_week = explode(',',$product['status_week']);
        if(!in_array($week,$status_week)){
            $order_day = \app\custom\Restaurant::getStatusWeek($status_week);
            if($order_day) $order_day = '，仅限'.$order_day;
            return $this->json(['status'=>0,'msg'=>'菜品今日不可点'.$order_day]);
        }
        if(!$post['ggid']){
			if($num > 0){
                $post['ggid'] = Db::name('restaurant_product_guige')->where('product_id',$post['proid'])->value('id');
                if(getcustom('restaurant_product_package')){
                    $post['ggid'] = 0 ;
                }
			}else{
				$post['ggid'] = Db::name('restaurant_shop_cart')->where('aid',aid)->where('mid',mid)->where('proid',$post['proid'])->order('id desc')->value('ggid');
			}
		}
        $is_check_guige_daily = 1;
        if(getcustom('restaurant_product_stock_daily')){
            if($product['total_stock_daily'] > 0){
                $is_check_guige_daily = 0;
                if($num > $product['total_stock_daily_real']){
                    return $this->json(['status'=>0,'msg'=>$product['name'].'的今日总库存不足']);
                }
            }
        } 
        if($post['ggid']){
            $guige =Db::name('restaurant_product_guige')->where('id',$post['ggid'])->find();
            if($guige['stock'] < $num ){
                return $this->json(['status'=>0,'msg'=>'库存不足']);
            }
            if(($guige['stock_daily']-$guige['sales_daily']<$num ) && $is_check_guige_daily){
                return $this->json(['status'=>0,'msg'=>'今日库存不足']);
            }
        }
		if($num > 0 && $product['limit_per'] > 0){ //每单限购
			$hasnum = Db::name('restaurant_shop_cart')->where('aid',aid)->where('mid',mid)->where('proid',$post['proid'])->sum('num');
			if($hasnum + $num > $product['limit_per']){
				return $this->json(['status'=>0,'msg'=>'每单限购'.$product['limit_per'].'份']);
			}
		}
		if($product['limit_start'] > 0){ //有起售数量
			$hasnum = Db::name('restaurant_shop_cart')->where('aid',aid)->where('mid',mid)->where('proid',$post['proid'])->sum('num');
			if($num > 0){ // +
				if($hasnum + $num < $product['limit_start']) $num = $product['limit_start'] - $hasnum;
			}else{ // -
				if($hasnum + $num < $product['limit_start']) $num = -$hasnum;
			}
		}
		//新增条件 加料判断
        $g_where[]= ['aid','=',aid];
        $g_where[]= ['proid','=',$post['proid']];
        $g_where[]= ['ggid','=',$post['ggid']];
        $is_user_mid =1;
        if(getcustom('restaurant_shop_pindan')){
            //先吃后付后续功能，以table为载体
            $bid = input('param.bid');
            $tableid = input('param.tableid');
            if($tableid >0){
                $is_user_mid = 0;
                $g_where[] = ['tableid','=',$tableid];
            }
        }
        if($is_user_mid)$g_where[]= ['mid','=',mid];
        if(getcustom('product_jialiao')){
            $jltitle = $post['jltitle']?$post['jltitle']:'';
            $g_where[]= ['jltitle','=',$jltitle];
        }
        if(getcustom('restaurant_product_jialiao')){
            $jldata = input('param.jldata');
            $jialiao = [];
            foreach($jldata as $key=>$val){
                if($val['num'] >0){
                    $jialiao[]=  $val;
                }
            }
            if($jialiao){
                $json_jialiao = json_encode($jialiao,JSON_UNESCAPED_UNICODE);
                $g_where[]= ['jldata','=',$json_jialiao];
            }else{
                $g_where[]= ['jldata','=',''];
            }
        }
        if(getcustom('restaurant_product_package')){
            if($package_data){
                $g_where[]= ['package_data','=',json_encode($package_data,JSON_UNESCAPED_UNICODE)];
            }
        }
		$gwc = Db::name('restaurant_shop_cart')->where($g_where)->find();
		if($gwc) $oldnum = $gwc['num'];

		if($oldnum + $num <=0){
			Db::name('restaurant_shop_cart')->where($g_where)->delete();
			$cartnum = Db::name('restaurant_shop_cart')->where('aid',aid)->where('mid',mid)->sum('num');
			return $this->json(['status'=>1,'msg'=>'移除成功','cartnum'=>$cartnum]);
		}
		if($gwc){
			Db::name('restaurant_shop_cart')->where($g_where)->inc('num',$num)->update();
            if(getcustom('product_jialiao')) {
                if (bccomp($gwc['jlprice'], $post['jlprice'], 2) != 0) {
                    Db::name('restaurant_shop_cart')->where($g_where)->update(['jlprice' => $post['jlprice']]);
                }
            }
            $cartid =  $gwc['id'];
		}else{
			$data = [];
			$data['aid'] = aid;
			$data['bid'] = $product['bid'];
			$data['mid'] = mid;
			$data['ggid'] = $post['ggid']?$post['ggid']:0;
			$data['createtime'] = time();
			$data['proid'] = $post['proid'];
			$data['num'] = $num;
			if(getcustom('product_jialiao')){
                $data['jlprice'] =$post['jlprice']?$post['jlprice']:0 ;
                $data['jltitle'] =$post['jltitle']?$post['jltitle']:'' ; 
            }
            if(getcustom('restaurant_product_jialiao')){
                $data['jldata'] = $jialiao?json_encode($jialiao,JSON_UNESCAPED_UNICODE):'';
            }
            if(getcustom('restaurant_product_package')){
                if($package_data){
                    $data['package_data'] = json_encode($package_data,JSON_UNESCAPED_UNICODE);
                    $data['package_price'] = dd_money_format($product['package_price'] + $post['add_price']);
                }
            }
            if(getcustom('restaurant_shop_pindan')){
                $tableid = input('param.tableid');
                $data['tableid']  = $tableid;
            }
            $cartid=Db::name('restaurant_shop_cart')->insertGetId($data);
		}
		$cartnum = Db::name('restaurant_shop_cart')->where('aid',aid)->where('mid',mid)->sum('num');
        $addmsg ='';
        if($product['name'] && $num >0){
            $addmsg = $product['name'].' x'.$num;
            $config = include(ROOT_PATH.'config.php');
            $authtoken = $config['authtoken'];
            $tableid = input('param.tableid');
            $token = md5(md5($authtoken.aid.$product['bid'].$tableid));
        }
		return $this->json(['status'=>1,'msg'=>'加入购物车成功','cartnum'=>$cartnum,'addmsg' => $addmsg]);
	}
	public function cartChangenum(){
		$this->checklogin();
		$id = input('post.id/d');
		$num = input('post.num/d');
		if($num < 1) $num = 1;
		Db::name('restaurant_shop_cart')->where('id',$id)->where('mid',mid)->update(['num'=>$num]);
		return $this->json(['status'=>1,'msg'=>'修改成功']);
	}
	public function cartdelete(){
		$this->checklogin();
		$id = input('post.id/d');
		if(!$id){
			$bid = input('post.bid/d');
			Db::name('restaurant_shop_cart')->where('bid',$bid)->where('mid',mid)->delete();
			return $this->json(['status'=>1,'msg'=>'删除成功']);
		}
		Db::name('restaurant_shop_cart')->where('id',$id)->where('mid',mid)->delete();
		return $this->json(['status'=>1,'msg'=>'删除成功']);
	}
	public function cartclear(){
		$bid = input('param.bid');
		if(!$bid) $bid = 0;
        $is_use_mid =1;
        if(getcustom('restaurant_shop_pindan')){
            $tableid = input('param.tableid');
            $table = Db::name('restaurant_table')->where('aid',aid)->where('id', $tableid)->find();
            if($tableid > 0 && $table['pindan_status'] ==1){
                $is_use_mid = 0;
                $cartwhere[] = ['tableid','=',$tableid];
            }
        }
        $cartwhere = [];
        $cartwhere[] =['aid','=',aid];
        $cartwhere[] =['bid','=',$bid];
        if($is_use_mid){
            $cartwhere[] =['mid','=',mid];
        }
		Db::name('restaurant_shop_cart')->where($cartwhere)->delete();
		return $this->json(['status'=>1,'msg'=>'删除成功']);
	}
	
	//获取促销信息
	public function getcuxiaoinfo(){
		$id = input('post.id/d');
		$info = Db::name('restaurant_cuxiao')->where('id',$id)->where('aid',aid)->find();
		if(!$info){
			return $this->json(['status'=>0,'msg'=>'获取失败']);
		}
		$proinfo = false;
		$gginfo = false;
		if(($info['type'] == 2 || $info['type'] == 3) && $info['proid']){
			$proinfo = Db::name('restaurant_product')->field('id,name,pic,sell_price')->where('aid',aid)->where('id',$info['proid'])->find();
			$gginfo = Db::name('restaurant_product_guige')->where('aid',aid)->where('id',$info['ggid'])->find();
		}
		return $this->json(['status'=>1,'info'=>$info,'product'=>$proinfo,'guige'=>$gginfo]);
	}
	//订单提交页
	public function buy(){
		$this->checklogin();
		$prodata = explode('-',input('param.prodata'));
		$tableid = input('param.tableId');
        $orderid = input('param.orderid');
        $isbook = input('param.isbook');
		$frompage = input('param.frompage');
		$is_bar_table =0;
		if(getcustom('restaurant_bar_table_order')){
            $mdid = input('param.mdid',0);
            if($tableid ==0 && $mdid){
                $is_bar_table = 1;
                $tableid = 0;
            }
        }
		//不是吧台点餐且tableid不存在
		if($is_bar_table==0 && !$tableid) return $this->json(['status'=>0,'msg'=>'请先扫描桌台二维码']);
		

		$tableinfo = Db::name('restaurant_table')->where('id',$tableid)->find();
        
		//桌子有订单号时,并且订单内有菜，为加菜
        $order = [];
        $is_check_table = 1; //是否检验桌台
        if(getcustom('restaurant_shop_pinzhuo')){
            //如果该桌台开启了拼桌模式，不再校验桌台
            $pinzhuo_status =  Db::name('restaurant_table')->where('aid', aid)->where('id', $tableid)->value('pinzhuo_status');
            if($pinzhuo_status ==1)$is_check_table = 0;
        }

        if(getcustom('restaurant_book_order') && $orderid){
            $tableinfo['orderid'] = $orderid;
        }
        if($tableinfo['orderid'] && !$isbook) {
            $order = Db::name('restaurant_shop_order')->where('aid', aid)->where('id', $tableinfo['orderid'])->find();
        }
        
        $is_create_order = 1; //是否是创建桌台订单
        if(getcustom('restaurant_shop_pindan')){
            if($tableinfo['pindan_status'] ==1 )$is_create_order=0;
        }
        //之前先吃后付的加菜走当前方法，现在走addToOrder方法，非admin加菜时这里只有create_order ,
        if($order && ($order['status'] == 0 && $frompage == 'admin' )){
            $ordertype = 'edit_order';
        } else{
            $ordertype = 'create_order';
        }
        
        if($is_check_table){
            if($order){
                 //默认创建订单，开启后才是编辑
                if($order['status'] > 0 && $ordertype =='create_order' )
                    return $this->json(['status'=>0,'msg'=>'当前桌台存在未结束的订单，请联系服务员清台后重新下单']);
                //桌台已有下单未支付时，自己的单跳转订单详情，其他人的单提示服务员处理
                if($tableinfo['orderid']  &&  $ordertype =='create_order' && $order['status'] ==0 && $order['eattype']==0 && $frompage !='admin'){
                    if(mid == $order['mid']){
                        return $this->json(['status'=>0,'msg' =>'已下单，去处理订单','url'=>'/restaurant/shop/orderdetail?id='.$order['id']]);
                    }else{
                        return $this->json(['status'=>0,'msg' =>'该桌台已存在订单，请呼叫服务员']);
                    }
                }
                $order['goods_count'] = Db::name('restaurant_shop_order_goods')->where('aid',aid)->where('orderid', $order['id'])->count();
            }else{
                //订单不存在 清台
                if(!$isbook){
                    Db::name('restaurant_table')->where('aid',aid)->where('id',$tableid)->update(['status' => 0, 'orderid' => 0]);
                }
                
            }
        }
      
 
//        $ordertype = $order && ($order['status'] == 0 || $frompage == 'admin') ? 'edit_order' : 'create_order';//加菜，点菜
		                                                                                                    
		$userlevel = Db::name('member_level')->where('aid',aid)->where('id',$this->member['levelid'])->find();
		$adminset = Db::name('admin_set')->where('aid',aid)->find();
		$userinfo = [];
		$userinfo['discount'] = $userlevel['discount'];
		$userinfo['score'] = $this->member['score'];
		$userinfo['score2money'] = $adminset['score2money'];
		$userinfo['scoredk_money'] = round($userinfo['score'] * $userinfo['score2money'],2);
		$userinfo['scoredkmaxpercent'] = $adminset['scoredkmaxpercent'];
        if(getcustom('sysset_scoredkmaxpercent_memberset')){
            //处理会员单独设置积分最大抵扣比例
            $userinfo['scoredkmaxpercent'] = $adminset['scoredkmaxpercent'] = \app\custom\ScoredkmaxpercentMemberset::dealmemberscoredk(aid,$this->member,$userinfo['scoredkmaxpercent']);
        }
		$userinfo['scoremaxtype'] = 0; //0最大百分比 1最大抵扣金额
		$userinfo['realname'] = $this->member['realname'];
		$userinfo['tel'] = $this->member['tel'];
		
		$scoredkmaxmoney = 0;
		$allbuydata = [];
		$autofahuo = 0;
		//订单存在，且未付款，且就餐类型是先吃后付
        //先吃后付，是已下单，读取后重查商品规格，返回需要的格式
        //先付后吃，未下单，执行购物车的查询操作，返回需要的格式
		if($order && $order['status']==0 && $order['eattype'] ==1){
		    if($order['settle_status'] ==1){//20250526 新增结算状态，解决重复使用优惠问题
		        $payorderid = Db::name('payorder')->where('aid',aid)->where('bid',$order['bid'])->where('orderid',$order['id'])->where('type','restaurant_shop')->value('id');
		        if($payorderid)  return $this->json(['status'=>0,'msg'=>'订单结算中','url' => '/pagesExt/pay/pay?id='.$payorderid]);
            }
            $goodslist = Db::name('restaurant_shop_order_goods')->where('aid',$order['aid'])->where('orderid',$order['id'])->select()->toArray();
            foreach($goodslist as $key=>$goods){
                $proid = $goods['proid'];
                $ggid = $goods['ggid'];
                $num = $goods['num'];
                $field = "id,aid,bid,cid,pic,name,sales,status_week,market_price,sell_price,lvprice,lvprice_data,freightdata,limit_per,scored_set,scored_val,status,start_time,end_time,start_hours,end_hours";
                if(getcustom('restaurant_weigh') || getcustom('restaurant_product_package')){
                    $field .=',product_type';
                }
                if(getcustom('restaurant_product_jialiao')){
                    $field .=',jl_is_discount';
                }
                if(getcustom('restaurant_product_package')){
                    $field .=',package_is_discount,package_is_coupon,package_is_cuxiao';
                }
                if(getcustom('restaurant_product_not_member_discount')){
                    $field .=',join_member_disount';
                }
                if(getcustom('restaurant_product_stock_daily')){
                    $field .= ",total_stock_daily_real,total_stock_daily";
                }
                $product = Db::name('restaurant_product')->field($field)->where('aid',aid)->where('ischecked',1)->where('id',$proid)->find();
                $guige = Db::name('restaurant_product_guige')->where('id',$ggid)->find();
                if(getcustom('restaurant_product_package')){
                    if($goods['package_data']){
                        $deletegg = 0;
                        $package_data = json_decode($goods['package_data'],true);
                        $ggtext = [];
                        foreach($package_data as $key=>$pd){
                            $t = 'x'.$pd['num'].' '.$pd['proname'];
                            if($pd['ggname'] !='默认规格'){
                                $t .='('.$pd['ggname'].')';
                            }
                            $ggtext[] = $t;
                        }
                        $guige['ggtext'] =$ggtext;
                        $guige['sell_price'] = $goods['package_price'];
                    }
                }
                $guige = $this->formatguige($guige,$product['bid'],$product['lvprice']);
                
                $jldata = ['jlprice' =>0,'jltitle' =>''];
                if(getcustom('product_jialiao')){
                    if($goods['jlprice'] >0)$jldata['jlprice'] = $goods['jlprice'];
                    
                    if($goods['jltitle'])$jldata['jltitle'] = $goods['jltitle'];
                }
                if(getcustom('restaurant_product_jialiao')){
                    if($goods['njlprice'] >0)$guige['sell_price'] = dd_money_format($guige['sell_price'] + $goods['njlprice']) ;
                    if($goods['njltitle'])$guige['name'] = $guige['name'].'('.rtrim($goods['njltitle'],'/').')';
                }
                if($product['bid']>0){
                    //判断商家是否能自主修改积分设置
                    $business_selfscore = 0;
                    if(getcustom('business_selfscore') || getcustom('business_score_jiesuan')){
                        $business_selfscore = Db::name('business_sysset')->where('aid',aid)->value('business_selfscore');
                    }
                    $bcansetscore = false;//商家能否修改积分
                    if(getcustom('business_cansetscore')){
                        //能否修改积分
                        if($product['bid']){
                            $business_cansetscore = Db::name('business')->where('id',$product['bid'])->value('business_cansetscore');
                            $bcansetscore = $business_cansetscore && $business_cansetscore == 1?true:false;
                        }
                    }
                    if(!$business_selfscore && !$bcansetscore){
                        $product['scored_set'] = 0;
                    }
                }
                if($product['scored_set']==0){
                    if($userinfo['scoredkmaxpercent'] == 0){
                        $userinfo['scoremaxtype'] = 1;
                        $scoredkmaxmoney += 0;
                    }else{
                        if($userinfo['scoredkmaxpercent'] > 0 && $userinfo['scoredkmaxpercent']<100){
                            $scoredkmaxmoney += $userinfo['scoredkmaxpercent'] * 0.01 * $guige['sell_price'] * $num;
                        }else{
                            $scoredkmaxmoney += $guige['sell_price'] * $num;
                        }
                    }
                }elseif($product['scored_set']==1){
                    $userinfo['scoremaxtype'] = 1;
                    $scoredkmaxmoney += $product['scored_val'] * 0.01 * $guige['sell_price'] * $num;
                }elseif($product['scored_set']==2){
                    $userinfo['scoremaxtype'] = 1;
                    $scoredkmaxmoney += $product['scored_val'] * $num;
                }else{
                    $userinfo['scoremaxtype'] = 1;
                    $scoredkmaxmoney += 0;
                }
                if(!$allbuydata[$product['bid']]) $allbuydata[$product['bid']] = [];
                if(!$allbuydata[$product['bid']]['prodata']) $allbuydata[$product['bid']]['prodata'] = [];
                $allbuydata[$product['bid']]['prodata'][] = ['product'=>$product,'guige'=>$guige,'num'=>$num,'jldata' =>$jldata,'carid' => 0,'remark' => $goods['remark'],'ogid' => $goods['id']];
            }
        }
		else{
            if(getcustom('restaurant_table_default_product')){
                if($ordertype =='create_order'){
                    $renshu = input('param.renshu');
                    if($tableinfo['default_product_bxdata']){
                        $bxdata = json_decode($tableinfo['default_product_bxdata'],true);
                        foreach($bxdata as $bxpro){     //437,1027,1,1791
                            $num = $bxpro['follow']==1 && $renshu?$renshu:$bxpro['num'] ;
                            $prodata[] = $bxpro['proid'].','.$bxpro['ggid'].','.$num.',0,'.'bx_'.$bxpro['follow'];
                        }
                    }
                    if($tableinfo['default_product_kxdata']){
                        $kxdata = json_decode($tableinfo['default_product_kxdata'],true);
                        foreach($kxdata as $kxpro){     //437,1027,1,1791
                            $num = $kxpro['follow']==1 && $renshu?$renshu:$kxpro['num'] ;
                            $prodata[] = $kxpro['proid'].','.$kxpro['ggid'].','.$num.',0,'.'kx_'.$kxpro['follow'];
                        }
                    }
                }
            }
            foreach($prodata as $key=>$gwc){
                list($proid,$ggid,$num,$carid) = explode(',',$gwc);
                $field = "id,aid,bid,cid,pic,name,sales,status_week,market_price,sell_price,lvprice,lvprice_data,freightdata,limit_per,scored_set,scored_val,status,start_time,end_time,start_hours,end_hours";
                if(getcustom('restaurant_weigh') || getcustom('restaurant_product_package')){
                    $field .=',product_type';
                }
                if(getcustom('restaurant_product_jialiao')){
                    $field .=',jl_is_discount';
                }
                if(getcustom('restaurant_product_package')){
                    $field .=',package_is_discount,package_is_coupon,package_is_cuxiao';
                }
                if(getcustom('restaurant_product_not_member_discount')){
                    $field .=',join_member_disount';
                }
                if(getcustom('restaurant_product_stock_daily')){
                    $field .= ",total_stock_daily_real,total_stock_daily";
                }
                $product = Db::name('restaurant_product')->field($field)->where('aid',aid)->where('ischecked',1)->where('id',$proid)->find();
                if(getcustom('restaurant_table_default_product')){
                    list($proid,$ggid,$num,$carid,$select_type) = explode(',',$gwc);
                    if($select_type){
                        $select_type =  explode('_',$select_type);
                        $product['select_type'] =  $select_type[0]??'';
                        $product['follow'] =  $select_type[1]??0;
                    }
                }
                if(!$product){
                    Db::name('restaurant_shop_cart')->where('aid',aid)->where('proid',$proid)->delete();
                    return $this->json(['status'=>0,'msg'=>'产品不存在或已下架']);
                }
                if($product['status']==0){
                    return $this->json(['status'=>0,'msg'=>'菜品未上架']);
                }
                if($product['status']==2 && (strtotime($product['start_time']) > time() || strtotime($product['end_time']) < time())){
                    return $this->json(['status'=>0,'msg'=>'菜品未上架']);
                }
                if($product['status']==3){
                    $start_time = strtotime(date('Y-m-d '.$product['start_hours']));
                    $end_time = strtotime(date('Y-m-d '.$product['end_hours']));
                    if(($start_time < $end_time && ($start_time > time() || $end_time < time())) || ($start_time >= $end_time && ($start_time > time() && $end_time < time()))){
                        return $this->json(['status'=>0,'msg'=>'菜品未上架']);
                    }
                }

                //周几可点
                $week = date("w");
                if($week==0) $week = 7;
                $status_week = explode(',',$product['status_week']);
                if(!in_array($week,$status_week)){
                    $order_day = \app\custom\Restaurant::getStatusWeek($status_week);
                    if($order_day) $order_day = '，仅限'.$order_day;
                    return $this->json(['status'=>0,'msg'=>'['.$product['name'].']今日不可点'.$order_day]);
                }
                if($product['limit_per'] > 0 && $num > $product['limit_per']){ //每单限购
                    return $this->json(['status'=>0,'msg'=>$product['name'].'每单限购'.$product['limit_per'].'份']);
                }
                if($product['limit_start'] > 0 && $num < $product['limit_start']){ //起售份数
                    return $this->json(['status'=>0,'msg'=>$product['name'].'最低购买'.$product['limit_start'].'份']);
                }
                if($product['limit_start'] > 0){ //有起售数量
                    $hasnum = Db::name('restaurant_shop_cart')->where('aid',aid)->where('mid',mid)->where('proid',$gwc['proid'])->sum('num');
                    if($num > 0){ // +
                        if($hasnum + $num < $product['limit_start']) $num = $product['limit_start'] - $hasnum;
                    }else{ // -
                        if($hasnum + $num < $product['limit_start']) $num = -$hasnum;
                    }
                }

                $guige = Db::name('restaurant_product_guige')->where('id',$ggid)->find();
                $deletegg = 1;
                if(getcustom('restaurant_product_package')){
                    $cartdata = Db::name('restaurant_shop_cart')->where('id',$carid) ->find();
                    if($cartdata['package_data']){
                        $deletegg = 0;
                        $guige['sell_price'] = $cartdata['package_price'];
                        $package_data = json_decode($cartdata['package_data'],true);
                        $ggtext = [];
                        foreach($package_data as $key=>$pd){
                            $t = 'x'.$pd['num'].' '.$pd['proname'];
                            if($pd['ggname'] !='默认规格'){
                                $t .='('.$pd['ggname'].')';
                            }
                            $ggtext[] = $t;
                        }
                        $guige['ggtext'] =$ggtext;
                    }
                }
                if(!$guige && $deletegg){
                    Db::name('restaurant_shop_cart')->where('aid',aid)->where('ggid',$ggid)->delete();
                    return $this->json(['status'=>0,'msg'=>'产品该规格不存在或已下架']);
                }
                $is_check_stock = 1;
                if(getcustom('restaurant_weigh')){
                    //称重商品不校验库存
                    if($product['product_type'] ==1){
                        $is_check_stock = 0;
                    }
                }
                if(getcustom('restaurant_product_package')){
                    if($product['product_type'] ==2){
                        $is_check_stock = 0;
                    }
                }
                $is_check_daily_stock = 1;

                if(getcustom('restaurant_product_stock_daily')){
                    if($product['total_stock_daily'] > 0){
                        $is_check_daily_stock = 0;
                        if($num > $product['total_stock_daily_real']){
                            return $this->json(['status'=>0,'msg'=>$product['name'].'的今日总库存不足']);
                        }
                    }
                }
                if($is_check_stock){
                    if($guige['stock'] < $num ){
                        return $this->json(['status'=>0,'msg'=>$product['name'].'库存不足']);
                    }
                    if($guige['stock_daily']-$guige['sales_daily']<$num && $is_check_daily_stock){
                        return $this->json(['status'=>0,'msg'=>$product['name'].'今日库存不足']);
                    }
                }

                //$gettj = explode(',',$product['gettj']);
                //if(!in_array('-1',$gettj) && !in_array($this->member['levelid'],$gettj) && (!in_array('0',$gettj) || $this->member['subscribe']!=1)){ //不是所有人
                //	if(!$product['gettjtip']) $product['gettjtip'] = '没有权限购买该菜品';
                //	return $this->json(['status'=>0,'msg'=>$product['gettjtip'],'url'=>$product['gettjurl']]);
                //}
                if($product['limit_per'] > 0){
                    if($num > $product['limit_per']){
                        return $this->json(['status'=>0,'msg'=>'每单限购'.$product['limit_per'].'件']);
                    }
                }
                $guige = $this->formatguige($guige,$product['bid'],$product['lvprice']);

                if($product['bid']>0){
                    //判断商家是否能自主修改积分设置
                    $business_selfscore = 0;
                    if(getcustom('business_selfscore') || getcustom('business_score_jiesuan')){
                        $business_selfscore = Db::name('business_sysset')->where('aid',aid)->value('business_selfscore');
                    }
                    $bcansetscore = false;//商家能否修改积分
                    if(getcustom('business_cansetscore')){
                        //能否修改积分
                        if($product['bid']){
                            $business_cansetscore = Db::name('business')->where('id',$product['bid'])->value('business_cansetscore');
                            $bcansetscore = $business_cansetscore && $business_cansetscore == 1?true:false;
                        }
                    }
                    if(!$business_selfscore && !$bcansetscore){
                        $product['scored_set'] = 0;
                    }
                }
                if($product['scored_set']==0){
                    if($userinfo['scoredkmaxpercent'] == 0){
                        $userinfo['scoremaxtype'] = 1;
                        $scoredkmaxmoney += 0;
                    }else{
                        if($userinfo['scoredkmaxpercent'] > 0 && $userinfo['scoredkmaxpercent']<100){
                            $scoredkmaxmoney += $userinfo['scoredkmaxpercent'] * 0.01 * $guige['sell_price'] * $num;
                        }else{
                            $scoredkmaxmoney += $guige['sell_price'] * $num;
                        }
                    }
                }elseif($product['scored_set']==1){
                    $userinfo['scoremaxtype'] = 1;
                    $scoredkmaxmoney += $product['scored_val'] * 0.01 * $guige['sell_price'] * $num;
                }elseif($product['scored_set']==2){
                    $userinfo['scoremaxtype'] = 1;
                    $scoredkmaxmoney += $product['scored_val'] * $num;
                }else{
                    $userinfo['scoremaxtype'] = 1;
                    $scoredkmaxmoney += 0;
                }

                if(!$allbuydata[$product['bid']]) $allbuydata[$product['bid']] = [];
                if(!$allbuydata[$product['bid']]['prodata']) $allbuydata[$product['bid']]['prodata'] = [];
                $jldata = ['jlprice' =>0,'jltitle' =>''];
                if(getcustom('product_jialiao')){
                    $jldata = Db::name('restaurant_shop_cart')->field('jlprice,jltitle')->where('id',$carid) ->find();
                    $input_jldata =   urldecode(input('jldata'));
                    if($input_jldata && input('btype') ==1){
                        $jlstring = explode('-',$input_jldata);
                        $jldata['jlprice'] = $jlstring[0];
                        $jldata['jltitle'] = $jlstring[1];
                    }
                }
                if(getcustom('restaurant_product_jialiao')){
                    $ncart = Db::name('restaurant_shop_cart')->field('jldata')->where('id',$carid) ->find();
                    if($ncart['jldata']){
                        $njldata = json_decode($ncart['jldata'],true);
                        $njlprice = 0;
                        $njltitle = '';
                        foreach($njldata as $key=>$val){
                            $njlprice += $val['num'] * $val['price'];
                            $njltitle .=$val['title'].'*'.$val['num'].'/';
                        }
                        $guige['sell_price'] = dd_money_format($guige['sell_price'] + $njlprice) ;
                        $guige['name'] = $guige['name'].'('.rtrim($njltitle,'/').')';
                        $product['njlprice'] = $njlprice;
                        $product['njltitle'] = $njltitle;
                    }
                }
                $allbuydata[$product['bid']]['prodata'][] = ['product'=>$product,'guige'=>$guige,'num'=>$num,'jldata' =>$jldata,'carid' => $carid,'remark' => ''];
            }
        }
	 
		$userinfo['scoredkmaxmoney'] = round($scoredkmaxmoney,2);
		
		$allproduct_price = 0;
		foreach($allbuydata as $bid=>$buydata){
			if($bid!=0){
				$business = Db::name('business')->where('id',$bid)->field('id,aid,cid,name,logo,tel,address,sales,longitude,latitude,start_hours,end_hours,is_open')->find();
                if($business['is_open']==0) return $this->json(['status'=>-4,'msg'=>$business['name'].'未营业']);
				if($business['start_hours'] != $business['end_hours']){
					$start_time = strtotime(date('Y-m-d '.$business['start_hours']));
					$end_time = strtotime(date('Y-m-d '.$business['end_hours']));
					if(($start_time < $end_time && ($start_time > time() || $end_time < time())) || ($start_time >= $end_time && ($start_time > time() && $end_time < time()))){
						return $this->json(['status'=>0,'msg'=>'商家不在营业时间']);
					}
				}
			}else{
				$business = Db::name('admin_set')->where('aid',aid)->field('id,name,logo,desc,tel')->find();
			}
			
			$shop_set = Db::name('restaurant_shop_sysset')->where('aid',aid)->where('bid',$bid)->find();
			if($shop_set['status']==0){
				return $this->json(['status'=>0,'msg'=>'商家未开启点餐']);
			}
			if($shop_set['start_hours'] != $shop_set['end_hours']){
				$start_time = strtotime(date('Y-m-d '.$shop_set['start_hours']));
				$end_time = strtotime(date('Y-m-d '.$shop_set['end_hours']));
				if(($start_time < $end_time && ($start_time > time() || $end_time < time())) || ($start_time >= $end_time && ($start_time > time() && $end_time < time()))){
					return $this->json(['status'=>0,'msg'=>'商家不在点餐时间']);
				}
			}
			
			$product_price = 0;
			$needzkproduct_price = 0;
			$notcuxiao_price = 0;//不需要促销的金额
            $notcoupon_price = 0; //不需要优惠券的金额
            $notcuxiao_num = 0;//不需要促销的数量
			$totalweight = 0;
			$totalnum = 0;
			$prodataArr = [];
			$proids = [];
			$cids = [];
			foreach($buydata['prodata'] as $prodata){
                $product_price += $prodata['guige']['sell_price']  * $prodata['num'];
                if(getcustom('product_jialiao')){
                    $product_price += $prodata['jldata']['jlprice'] *  $prodata['num'];
                }
                $is_add_zkprice = 1;
                if(getcustom('restaurant_product_not_member_discount')){
                    if(!$prodata['product']['join_member_disount'])$is_add_zkprice=0;//不参与会员折扣
                }
				if($is_add_zkprice && $prodata['product']['lvprice']==0){ //未开启会员价
					$needzkproduct_price += $prodata['guige']['sell_price'] * $prodata['num'];
				}
                $ogid = $prodata['ogid'];//当前的ordergoodsid
                $ordergoodsdata = [];
                if($ogid){
                    $ordergoodsdata = Db::name('restaurant_shop_order_goods')->where('aid',aid)->where('id',$ogid)->find();
                }
                if(getcustom('restaurant_product_jialiao')){
                    //如果商品设置打折
                    $cartid  =  $prodata['carid'];//购物车
                    $jldata = Db::name('restaurant_shop_cart')->where('id',$cartid)->value('jldata');
                    if($jldata){
                        $njldata = json_decode($jldata,true);
                        $njlprice = 0;
                        $njltitle = '';
                        foreach($njldata as $key=>$val){
                            $njlprice += $val['num'] * $val['price'];
                            $njltitle .=$val['title'].'*'.$val['num'].'/';
                        }
                        if($prodata['product']['jl_is_discount'] ==0){
                            $needzkproduct_price -= $njlprice;
                        }
                    }else{
                        $njlprice =$ordergoodsdata['njlprice'];
                        if($prodata['product']['jl_is_discount'] ==0){
                            $needzkproduct_price -= $njlprice;
                        }
                    }
                }
                if(getcustom('restaurant_product_package')){
                    $cartdata = Db::name('restaurant_shop_cart')->where('id',$prodata['carid'])->find();
                    if($prodata['product']['product_type'] ==2 && !$prodata['product']['package_is_discount']){
                        $needzkproduct_price -= $cartdata['package_price'] *$cartdata['num'];
                    }
                    if($prodata['product']['product_type'] ==2 && !$prodata['product']['package_is_cuxiao']){
                        $notcuxiao_price += $cartdata['package_price'] *$cartdata['num'];
                        $notcuxiao_num +=$cartdata['num'];
                    }
                    if($prodata['product']['product_type'] ==2 && !$prodata['product']['package_is_coupon']){
                        $notcoupon_price += $cartdata['package_price'] *$cartdata['num'];
                    }
                }
				$totalweight += $prodata['guige']['weight'] * $prodata['num'];
				$totalnum += $prodata['num'];
				$prodataArr[] = $prodata['product']['id'].','.$prodata['guige']['id'].','.$prodata['num'].','.$prodata['carid'];
				$proids[] = $prodata['product']['id'];
				$cids = array_merge(explode(',',$prodata['product']['cid']),$cids);
			}
			$prodatastr = implode('-',$prodataArr);
			
			$leveldk_money = 0;
			if($userlevel && $userlevel['discount']>0 && $userlevel['discount']<10){
				$leveldk_money = $needzkproduct_price * (1 - $userlevel['discount'] * 0.1);
			}
			$leveldk_money = round($leveldk_money,2);
			$price = $product_price - $leveldk_money;
			if($ordertype == 'create_order') {
                //满减活动，使用餐饮-促销
                $manjian_money = 0;
                    $allbuydata[$bid]['manjian_money'] = 0;
                $newcouponlist = [];
                $coupon_bid = [$bid,'-1'];
                if(getcustom('restaurant_coupon_apply_business')){
                    if($bid > 0)$coupon_bid[]= 0;
                } 
                $couponwhere = [];
                $couponwhere[] = ['aid','=',aid];
                $couponwhere[] = ['bid','in',$coupon_bid];
                $couponwhere[] = ['mid','=',mid];
                $couponwhere[] = ['status','=',0];
                $couponwhere[] = ['minprice','<=',$price - $manjian_money - $notcoupon_price];
                $couponwhere[] = ['starttime','<=',time()];
                $couponwhere[] = ['endtime','>',time()];
                $coupontype = [1,4,5];
                if(getcustom('restaurant_cashdesk_discount_coupon'))$coupontype[] = 10;//折扣券
                $couponwhere[] = ['type','in',$coupontype];
                $couponList = Db::name('coupon_record')
                    ->where($couponwhere)
                    ->order('id desc')->select()->toArray();
                if(!$couponList) $couponList = [];
                foreach($couponList as $k=>$v){
                    //$couponList[$k]['starttime'] = date('m-d H:i',$v['starttime']);
                    //$couponList[$k]['endtime'] = date('m-d H:i',$v['endtime']);
                    $couponinfo = Db::name('coupon')->where('aid',aid)->where('id',$v['couponid'])->find();
                    if(empty($couponinfo)) continue;
                    if($couponinfo['fwscene']!==0){
                        continue;
                    }
                    // 仅转增
                    if($couponinfo['isgive'] == 2 && empty($v['from_mid'])){
                        continue;
                    }

                    $v['thistotalprice'] = $price - $manjian_money;
                    $v['couponmoney'] = $v['money'];//可抵扣金额
                    if($couponinfo['fwtype']==2){//指定菜品可用
                        $productids = explode(',',$couponinfo['productids']);
                        if(!array_intersect($proids,$productids)){
                            continue;
                        }
                        $thistotalprice = 0;
                        foreach($buydata['prodata'] as $k2=>$v2){
                            $product = $v2['product'];
                            if(in_array($product['id'],$productids)){
                                $thistotalprice += $v2['guige']['sell_price'] * $v2['num'];
                            }
                        }
                        if($thistotalprice < $v['minprice']){
                            continue;
                        }
                        $v['thistotalprice'] = $thistotalprice;
                        $v['couponmoney'] = min($thistotalprice,$v['money']);//可抵扣金额
                    }

                    if($couponinfo['fwtype']==1){//指定类目可用
                        $categoryids = explode(',',$couponinfo['categoryids']);
                        $clist = Db::name('restaurant_product_category')->where('pid','in',$categoryids)->select()->toArray();
                        foreach($clist as $kc=>$vc){
                            $categoryids[] = $vc['id'];
                            $cate2 = Db::name('restaurant_product_category')->where('pid',$vc['id'])->find();
                            $categoryids[] = $cate2['id'];
                        }
                        if(!array_intersect($cids,$categoryids)){
                            continue;
                        }
                        $thistotalprice = 0;
                        foreach($buydata['prodata'] as $k2=>$v2){
                            $product = $v2['product'];
                            if(array_intersect(explode(',',$product['cid']),$categoryids)){
                                $thistotalprice += $v2['guige']['sell_price'] * $v2['num'];
                            }
                        }
                        if($thistotalprice < $v['minprice']){
                            continue;
                        }
                        $v['thistotalprice'] = $thistotalprice;
                        $v['couponmoney'] = min($thistotalprice,$v['money']);//可抵扣金额
                    }
                    if(getcustom('restaurant_coupon_apply_business')){
                        //是平台且 当前优惠券 不适用平台
                        if($bid==0 && $couponinfo['apply_platform'] ==0)continue;
                        $businessids = explode(',',$couponinfo['apply_businessids']);
                        if($bid > 0 && !in_array($bid,$businessids ) && $couponinfo['apply_business_type'] ==1){
                            continue;
                        }
                    }
                    $newcouponlist[] = $v;
                }
                $couponList = $newcouponlist;

                //促销活动
                $swhere = '';
                $totalnum = $totalnum - $notcuxiao_num;
                if(getcustom('restaurant_the_second_discount')){
                    if($totalnum > 1){
                        $swhere = 'or (type=7)';
                    }
                }
                $cuxiao_price =  $price - $manjian_money - $notcuxiao_price;
                $cuxiaolist = Db::name('restaurant_cuxiao')->where('aid',aid)->where('bid',$bid)->where("(type in (1,2,3,4) and minprice<=".($cuxiao_price).") or ((type=5 or type=6) and minnum<=".$totalnum.") ".$swhere)->where('starttime','<',time())->where('endtime','>',time())->order('sort desc')->select()->toArray();
                $newcxlist = [];
                foreach($cuxiaolist as $k=>$v){
                    $gettj = explode(',',$v['gettj']);
                    if(!in_array('-1',$gettj) && !in_array($this->member['levelid'],$gettj)){ //不是所有人
                        continue;
                    }
                    if(getcustom('restaurant_cuxiao_activity_day')){
                        //促销活动日
                        if($v['activity_day_type'] ==0){//周几
                            $now_week = date('w');
                            $activity_day_week = explode(',',$v['activity_day_week']);
                            if(!in_array($now_week,$activity_day_week)){
                                continue;
                            }
                        }else{//几号
                            $now_date = date('d');
                            $activity_day_date = explode(',',$v['activity_day_week']);
                            if(!in_array($now_date,$activity_day_date)){
                                continue;
                            }
                        }
                    }
                    if(getcustom('restaurant_cuxiao_use_time_range')){
                        $now_time =strtotime(date('H:i:s'));
                        if($v['use_starttime'] && $v['use_endtime'] && ( $now_time < strtotime($v['use_starttime']) || $now_time > strtotime($v['use_endtime']))){
                            continue;
                        }
                    }
                    //多时间段
                    if(getcustom('restaurant_cuxiao_multi_use_time_range')){
                        $multi_time_range = json_decode($v['multi_time_range'],true);
                        if($multi_time_range){
                            $now_time =strtotime(date('H:i'));
                            $is_rangetime = 0;
                            foreach($multi_time_range as $rangetime){
                                if($now_time > strtotime($rangetime['starttime'])  && $now_time < strtotime($rangetime['endtime'])){
                                    $is_rangetime =1;
                                }
                            }
                            if(!$is_rangetime)continue;
                        }
                    }
                    if(getcustom('restaurant_first_pay_shop_canuse')){
                        //先付后吃，扫码点餐可用
                        if($tableinfo['pindan_status'] ==0 && $v['first_pay_shop_canuse'] ==0){
                            continue;
                        }
                    }
                 
                    if($v['fwtype']==2){//指定菜品可用
                        $productids = explode(',',$v['productids']);
                        if(!array_intersect($proids,$productids)){
                            continue;
                        }
                        if($v['type']==1 || $v['type']==2 || $v['type']==3 || $v['type']==4){//指定菜品是否达到金额要求
                            $cuxiao_product_total = 0;
                            foreach($buydata['prodata'] as $vpro){
                                if(in_array($vpro['product']['id'], $productids)){
                                    $this_cuxiao_product_total = $vpro['guige']['sell_price'] * $vpro['num'];
                                    if(getcustom('restaurant_product_package')){
                                        if($vpro['product']['product_type'] ==2 && $vpro['product']['package_is_coupon'] ==1){
                                            $cartdata = Db::name('restaurant_shop_cart')->where('id',$vpro['cartid'])->find();
                                           $this_cuxiao_product_total = $cartdata['package_price'] * $cartdata['num'];
                                        }
                                        
                                    }
                                    $cuxiao_product_total += $this_cuxiao_product_total;
                                }
                            }
                            if($cuxiao_product_total < $v['minprice']){
                                continue;
                            }
                        }
                        if($v['type']==6 || $v['type']==5){//指定菜品是否达到件数要求
                            $thistotalnum = 0;
                            foreach($buydata['prodata'] as $vpro){
                                if(in_array($vpro['product']['id'], $productids)){
                                    $thistotalnum += $vpro['num'];
                                }
                            }
                            if($thistotalnum < $v['minnum']){
                                continue;
                            }
                        }
                    }
                    if($v['fwtype']==1){//指定类目可用
                        $categoryids = explode(',',$v['categoryids']);
                        $clist = Db::name('restaurant_product_category')->where('pid','in',$categoryids)->select()->toArray();
                        foreach($clist as $kc=>$vc){
                            $categoryids[] = $vc['id'];
                            $cate2 = Db::name('restaurant_product_category')->where('pid',$vc['id'])->find();
                            $categoryids[] = $cate2['id'];
                        }
                        if(!array_intersect($cids,$categoryids)){
                            continue;
                        }
                        if($v['type']==1 || $v['type']==2 || $v['type']==3 || $v['type']==4){//指定菜品是否达到金额要求
                            $cuxiao_cate_total = 0;
                            foreach($buydata['prodata'] as $vpro){
                                $cuxiao_pro_cidArr = explode(',',$vpro['product']['cid']);
                                if(array_intersect($cuxiao_pro_cidArr, $categoryids)){
                                    $cuxiao_cate_total += $vpro['guige']['sell_price'] * $vpro['num'];
                                }
                            }
                            if($cuxiao_cate_total < $v['minprice']){
                                continue;
                            }
                        }
                        if($v['type']==6 || $v['type']==5){//指定类目内菜品是否达到件数要求
                            $thistotalnum = 0;
                            foreach($buydata['prodata'] as $vpro){
                                $cuxiao_pro_cidArr = explode(',',$vpro['product']['cid']);
                                if(array_intersect($cuxiao_pro_cidArr, $categoryids)){
                                    $thistotalnum += $vpro['num'];
                                }
                            }
                            if($thistotalnum < $v['minnum']){
                                continue;
                            }
                        }
                    }
                    if(getcustom('restaurant_the_second_discount')){
                        //第二件折扣时,判断是同产品 还是非同产品，如果必须同产品 判断是否有购买2件以上的，否则不可用
                        if($v['is_one_product'] ==1 && $v['type'] ==7){//判断是否必须同一件商品
                            $is_have_two = 0;
                            foreach ($buydata['prodata'] as $gk => $gv) {
                                if($gv['num'] > 1){
                                    $is_have_two = 1;
                                }
                            }
                            if($is_have_two ==0){
                                continue;
                            }
                        }
                    }
                    $newcxlist[] = $v;
                }

                $allbuydata[$bid]['couponList'] = $couponList;
                $allbuydata[$bid]['couponCount'] = count($couponList);
                $allbuydata[$bid]['tea_fee'] = $shop_set['tea_fee_status']==1 ? round($shop_set['tea_fee'],2) : 0;
                if(getcustom('restaurant_bar_table_order')){
                    if($shop_set['bar_table_order'] ==1){
                        $allbuydata[$bid]['tea_fee'] = 0;
                    }
                }
                $allbuydata[$bid]['tea_fee_text'] = $shop_set['tea_fee_text'];
                $allbuydata[$bid]['coupon_money'] = 0;
                $allbuydata[$bid]['coupontype'] = 1;
                $allbuydata[$bid]['couponrid'] = 0;
                $allbuydata[$bid]['cuxiaolist'] = $newcxlist;
                $allbuydata[$bid]['cuxiaoCount'] = count($newcxlist);
                $allbuydata[$bid]['cuxiao_money'] = 0;
                $allbuydata[$bid]['cuxiaotype'] = 0;
                $allbuydata[$bid]['cuxiaoid'] = 0;
                $allbuydata[$bid]['renshu'] = 0;
            } elseif($ordertype == 'edit_order') {
                $allbuydata[$bid]['coupon_money'] = 0;
                $allbuydata[$bid]['cuxiao_money'] = 0;
                $allbuydata[$bid]['tea_fee'] = 0;
                $allbuydata[$bid]['manjian_money'] = 0;
                $allbuydata[$bid]['renshu'] = 0;
            }

			$allbuydata[$bid]['bid'] = $bid;
			$allbuydata[$bid]['business'] = $business;
			$allbuydata[$bid]['prodatastr'] = $prodatastr;
			$allbuydata[$bid]['product_price'] = round($product_price,2);
			$allbuydata[$bid]['not_cuxiao_price'] = round($notcuxiao_price,2);
			$allbuydata[$bid]['not_coupon_price'] = round($notcoupon_price,2);
			$allbuydata[$bid]['needzkproduct_price'] = round($needzkproduct_price,2);
            $allbuydata[$bid]['leveldk_money'] = $leveldk_money;
            $allbuydata[$bid]['message'] = '';
            $allbuydata[$bid]['field1'] = '';
            $allbuydata[$bid]['field2'] = '';
            $allbuydata[$bid]['field3'] = '';
            $allbuydata[$bid]['field4'] = '';
            $allbuydata[$bid]['field5'] = '';
			$allproduct_price += $product_price;
		}
      
		$rdata = [];
		$rdata['status'] = 1;
		$rdata['linkman'] = $userinfo['realname'] ? strval($userinfo['realname']) : strval($userinfo['nickname']);
		$rdata['tel'] = strval($userinfo['tel']);
		$rdata['userinfo'] = $userinfo;
		$rdata['allbuydata'] = $allbuydata;
		$rdata['scorebdkyf'] = Db::name('admin_set')->where('aid',aid)->value('scorebdkyf');
		$rdata['order'] = $order ? $order : [];
        $rdata['ordertype'] = $ordertype;
		$rdata['tableinfo'] = $tableinfo;
        $rdata['is_bar_table'] = $is_bar_table;
        if(getcustom('restaurant_bar_table_order')){
            $mdid = input('param.mdid');
            $mdinfo = Db::name('mendian')->where('id',$mdid)->field('id,name,address,longitude,latitude,province,city,district')->find();
            $rdata['mdinfo'] = $mdinfo;
        }
        if(getcustom('restaurant_take_food')) {
            $tmplids = [];
            $restaurant_take_food_sysset = Db::name('restaurant_take_food_sysset')->where('aid',aid)->find();
            if($restaurant_take_food_sysset['status'] ==1) {
                if (platform == 'wx') {
                    $wx_tmplset = Db::name('wx_tmplset')->where('aid', aid)->find();
                    if ($wx_tmplset['tmpl_take_food']) {
                        $tmplids[] = $wx_tmplset['tmpl_take_food'];
                    }
                }
                if (platform == 'alipay') {
                    $tmpl_take_food = Db::name('admin_setapp_alipay')->where('aid', aid)->value('tmpl_take_food');
                    if($tmplids){
                        $tmplids[] = $tmpl_take_food;
                    }
                }
            }
            $rdata['tmplids'] = $tmplids??[];
        }
        $change_people_number = 1;
        if(getcustom('restaurant_shop_select_renshu')){
            $select_renshu_status = Db::name('restaurant_shop_sysset')->where('aid',aid)->value('select_renshu_status');
            //是否选择人数
            $change_people_number = $select_renshu_status;
        }
        $rdata['change_people_number'] = $change_people_number;
        if(getcustom('restaurant_shop_pindan')){
            $config = include(ROOT_PATH.'config.php');
            $authtoken = $config['authtoken'];
            $rdata['token'] = md5(md5($authtoken.aid.$tableinfo['bid'].$tableinfo['id']));
        }
		return $this->json($rdata);
	}
	public function createOrder(){
        $post = input('post.');
        $eattype =input('param.eattype');
        if($post['frompage'] != 'admin') {
            //非管理员点餐验证登录
            $this->checklogin();
        }
        $buydata = $post['buydata'];
        $shop_sysset = Db::name('restaurant_shop_sysset')->where('aid',aid)->where('bid',$buydata[0]['bid'])->find();
        $mdid = input('param.mdid',0);
        
        $is_bar_table =0;
        if(getcustom('restaurant_bar_table_order')){
            if($mdid && $post['tableid'] ==0){
                $is_bar_table = 1;
                $tableid = 0;
            }
        }
		if(empty($post['tableid']) && $is_bar_table==0) {
            return $this->json(['status'=>0,'msg'=>'请先扫描桌台二维码或选择桌台']);
        }

		//todo 一个桌子同时只能点一单
        $table = Db::name('restaurant_table')->where('aid',aid)->where('id', $post['tableid'])->find();
		//是否校验桌台
        $is_check_table = true;
        if(getcustom('restaurant_shop_pinzhuo')){
            //如果该桌台开启了拼桌模式，不再校验桌台
            $pinzhuo_status =  Db::name('restaurant_table')->where('aid', aid)->where('id', $tableid)->value('pinzhuo_status');
            if($pinzhuo_status==1)   $is_check_table = false;
        }
        if(getcustom('restaurant_shop_pindan') && $table){
            if($table['pindan_status'] ==0)$is_check_table=false;
        }
        if($is_check_table){
            if($table) {
                $isbook = input('param.isbook');
               
                if($table['orderid'] && !$isbook && $eattype==0) {
                    //修改菜品
                    return $this->json(['status'=>-4,'msg'=>'当前桌台已存在订单，请重新下单','url'=>'/restaurant/shop/index?tableId='.$post['tableid'].'&bid='.$buydata[0]['bid']]);
                }
            }else{
                if($is_bar_table==0){
                    return $this->json(['status'=>0,'msg'=>'桌台数据异常，请联系服务员']);
                }
            }
        }

        $sysset = Db::name('admin_set')->where('aid',aid)->find();
        if(getcustom('sysset_scoredkmaxpercent_memberset')){
            //处理会员单独设置积分最大抵扣比例
            $sysset['scoredkmaxpercent'] = \app\custom\ScoredkmaxpercentMemberset::dealmemberscoredk(aid,$this->member,$sysset['scoredkmaxpercent']);
        }
		$userlevel = Db::name('member_level')->where('aid',aid)->where('id',$this->member['levelid'])->find();

		$couponridArr = [];
		foreach($buydata as $data){ //判断有没有重复选择的优惠券
			if($data['couponrid'] && in_array($data['couponrid'],$couponridArr)){
				return $this->json(['status'=>0,'msg'=>t('优惠券').'不可重复使用']);
			}elseif($data['couponrid']){
				$couponridArr[] = $data['couponrid'];
			}
		}

		$ordernum = date('ymdHis').rand(100000,999999);
		$i = 0;
		$alltotalprice = 0;
		$alltotalscore = 0;

        if(getcustom('member_level_moneypay_price')){
            $alltotalputongprice = 0;//所有商品普通价格总价
        }

		foreach($buydata as $data){
            $scoredkmaxmoney = 0;//商家累加积分抵扣
            $scoremaxtype = 0;

			$i++;
			$bid = $data['bid'];
			if($data['prodata']){
				$prodata = explode('-',$data['prodata']);
			}else{
				return $this->json(['status'=>0,'msg'=>'产品数据错误']);
			}
			if($bid!=0){
				$business = Db::name('business')->where('id',$bid)->field('id,aid,cid,name,logo,tel,address,sales,longitude,latitude,start_hours,end_hours,is_open')->find();
                if($business['is_open']==0) return $this->json(['status'=>-4,'msg'=>$business['name'].'未营业']);
                if($business['start_hours'] != $business['end_hours']){
					$start_time = strtotime(date('Y-m-d '.$business['start_hours']));
					$end_time = strtotime(date('Y-m-d '.$business['end_hours']));
					if(($start_time < $end_time && ($start_time > time() || $end_time < time())) || ($start_time >= $end_time && ($start_time > time() && $end_time < time()))){
						return $this->json(['status'=>0,'msg'=>'商家不在营业时间']);
					}
				}
			}
			$shop_set = Db::name('restaurant_shop_sysset')->where('aid',aid)->where('bid',$bid)->find();
			if($shop_set['status']==0){
				return $this->json(['status'=>0,'msg'=>'该商家未开启点餐']);
			}
			if($shop_set['start_hours'] != $shop_set['end_hours']){
				$start_time = strtotime(date('Y-m-d '.$shop_set['start_hours']));
				$end_time = strtotime(date('Y-m-d '.$shop_set['end_hours']));
				if(($start_time < $end_time && ($start_time > time() || $end_time < time())) || ($start_time >= $end_time && ($start_time > time() && $end_time < time()))){
					return $this->json(['status'=>0,'msg'=>'该商家不在点餐时间']);
				}
			}

			$product_price = 0;
			$needzkproduct_price = 0;
            $notcuxiao_price = 0;//不需要促销的金额
            $notcoupon_price = 0; //不需要优惠券的金额
			$givescore = 0; //奖励积分
			$totalweight = 0;//重量
			$totalnum = 0;
			$prolist = [];
			$proids = [];
			$cids = [];
            $ogids = $data['ogid'];//先吃后付时的ogid集合
            if(getcustom('member_level_moneypay_price')){
                $product_price_cha = 0;//普通价格与会员购买价格的差额
            }

			foreach($prodata as $key=>$pro){
				$sdata = explode(',',$pro);
				$sdata[2] = intval($sdata[2]);
				if($sdata[2] <= 0) return $this->json(['status'=>0,'msg'=>'购买数量有误']);
				$product = Db::name('restaurant_product')->where('aid',aid)->where('ischecked',1)->where('bid',$bid)->where('id',$sdata[0])->find();
				if(!$product) return $this->json(['status'=>0,'msg'=>'产品不存在或已下架']);
				
				if($product['status']==0){
					return $this->json(['status'=>0,'msg'=>'菜品未上架']);
				}
				if($product['status']==2 && (strtotime($product['start_time']) > time() || strtotime($product['end_time']) < time())){
					return $this->json(['status'=>0,'msg'=>'菜品未上架']);
				}
				if($product['status']==3){
					$start_time = strtotime(date('Y-m-d '.$product['start_hours']));
					$end_time = strtotime(date('Y-m-d '.$product['end_hours']));
					if(($start_time < $end_time && ($start_time > time() || $end_time < time())) || ($start_time >= $end_time && ($start_time > time() && $end_time < time()))){
						return $this->json(['status'=>0,'msg'=>'菜品未上架']);
					}
				}
				
				if($key==0) $title = $product['name'];

				$guige = Db::name('restaurant_product_guige')->where('aid',aid)->where('id',$sdata[1])->find();
                $cartdata = Db::name('restaurant_shop_cart')->where('id',$sdata[3]) ->find();
                $ogid = $ogids[$key];//当前的ordergoodsid
                $ordergoodsdata = [];
                if($ogid){
                    $ordergoodsdata = Db::name('restaurant_shop_order_goods')->where('aid',aid)->where('id',$ogid)->find();
                }
                $num = $sdata[2];
                $deletegg = 1;
                if(getcustom('restaurant_product_package')){
                    if($product['product_type'] ==2){
                        $deletegg = 0;
                        //判断套餐是否餐与
                        if($cartdata ){
                            $package_price= $cartdata['package_price'];
                        } else{
                            $package_price= $ordergoodsdata['package_price'];
                        }

                        if($product['product_type'] ==2 && $product['package_is_discount']==1){
                            $needzkproduct_price +=$package_price *$num;
                        }
                        if($product['product_type'] ==2 && !$product['package_is_cuxiao']){
                            $notcuxiao_price += $cartdata['package_price'] *$num;
                        }
                        if($product['product_type'] ==2 && !$product['package_is_coupon']){
                            $notcoupon_price += $cartdata['package_price'] *$num;
                        }
                        $guige['sell_price'] = $package_price;
                    }
                }
				if(!$guige && $deletegg) return $this->json(['status'=>0,'msg'=>'产品规格不存在或已下架']);
                $is_check_stock = 1;
                if(getcustom('restaurant_weigh')){
                    if($product['product_type'] ==1){
                        //称重商品不校验库存
                        $is_check_stock = 0;
                    }
                }
                if(getcustom('restaurant_product_package')){
                    if($product['product_type'] ==2){
                        $is_check_stock = 0;
                    }
                }
                $is_check_daily_stock = 1;
                if(getcustom('restaurant_product_stock_daily')){
                    if($product['total_stock_daily'] > 0){
                        $is_check_daily_stock = 0;
                        if($sdata[2] > $product['total_stock_daily_real']){
                            return $this->json(['status'=>0,'msg'=>$product['name'].'的今日总库存不足']);
                        }
                    }
                }
                if($is_check_stock){
                    if($guige['stock'] < $sdata[2] ){
                        return $this->json(['status'=>0,'msg'=>$product['name'].'库存不足']);
                    }
                    if($guige['stock_daily']-$guige['sales_daily']<$sdata[2] && $is_check_daily_stock){
                        return $this->json(['status'=>0,'msg'=>$product['name'].'今日库存不足']);
                    }
                }
				//$gettj = explode(',',$product['gettj']);
				//if(!in_array('-1',$gettj) && !in_array($this->member['levelid'],$gettj) && (!in_array('0',$gettj) || $this->member['subscribe']!=1)){ //不是所有人
				//	if(!$product['gettjtip']) $product['gettjtip'] = '没有权限购买该菜品';
				//	return $this->json(['status'=>0,'msg'=>$product['gettjtip'],'url'=>$product['gettjurl']]);
				//}
				if($product['limit_per'] > 0 && $sdata[2] > $product['limit_per']){ //每单限购
					return $this->json(['status'=>0,'msg'=>$product['name'].'每单限购'.$product['limit_per'].'份']);
				}
				if($product['limit_start'] > 0 && $sdata[2] < $product['limit_start']){ //起售份数
					return $this->json(['status'=>0,'msg'=>$product['name'].'最低购买'.$product['limit_start'].'份']);
				}

                if(getcustom('member_level_moneypay_price')){
                    $guige['sell_putongprice']= $guige['sell_price'];//当前商品普通价格
                    $pre_product_putongprice  = $guige['sell_price'] * $sdata[2];//当前数量商品普通价格
                }

                $guige = $this->formatguige($guige,$product['bid'],$product['lvprice']);
               
				if(getcustom('product_jialiao')){
                    $cart=Db::name('restaurant_shop_cart')->where('aid',aid)->where('mid',mid)->where('ggid',$guige['id'])->where('proid',$product['id'])-> find();
                    if($cart){
                        $product_price += $cart['jlprice'] * $sdata[2] ;
                    }
                    $input_jldata =   urldecode(input('jldata'));
                    if(empty($cart) && $input_jldata){
                        $jlstring = explode('-',$input_jldata);
                        $product_price += $jlstring[0] * $sdata[2] ;
                    }
                    if($ordergoodsdata && $ordergoodsdata['jlprice'] > 0){
                        $product_price +=  $ordergoodsdata['jlprice'] * $num;
                    }
                }
				$is_add_zkprice = 1;//是否计算打折扣金额中
				if(getcustom('restaurant_product_not_member_discount')){
				    if(!$product['join_member_disount'])$is_add_zkprice=0;//不参与会员折扣
                }
				if($is_add_zkprice && $product['lvprice']==0){ //未开启会员价
					$needzkproduct_price += $guige['sell_price'] * $sdata[2];
				}
                $cartid  =  intval($sdata[3]);//购物车
                if(getcustom('restaurant_product_jialiao')){
                    //如果商品设置打折
                    $jldata = Db::name('restaurant_shop_cart')->where('id',$cartid)->value('jldata');
                    $njlprice = 0;
                    $njltitle = '';
                    if($jldata){
                        $njldata = json_decode($jldata,true);
                        foreach($njldata as $key=>$val){
                            $njlprice += $val['num'] * $val['price']* $sdata[2];
                            $njltitle .=$val['title'].'*'.$val['num'].'/';
                        }
                        $njltitle = rtrim($njltitle,'/');
                    }else{
                        $njlprice = $ordergoodsdata['njlprice'];
                        $njltitle = $ordergoodsdata['njltitle'];
                    }
                    if($product['jl_is_discount'] ==1){
                        $needzkproduct_price += $njlprice * $sdata[2];
                    }
                   
                    $product_price +=  $njlprice * $sdata[2];
                }
				$totalweight += $guige['weight'] * $sdata[2];
				$totalnum += $sdata[2];
			    
                if($product['bid']>0){
                    //判断商家是否能自主修改积分设置
                    $business_selfscore = 0;
                    if(getcustom('business_selfscore') || getcustom('business_score_jiesuan')){
                        $business_selfscore = Db::name('business_sysset')->where('aid',aid)->value('business_selfscore');
                    }
                    $bcansetscore = false;//商家能否修改积分
                    if(getcustom('business_cansetscore')){
                        //能否修改积分
                        if($product['bid']){
                            $business_cansetscore = Db::name('business')->where('id',$product['bid'])->value('business_cansetscore');
                            $bcansetscore = $business_cansetscore && $business_cansetscore == 1?true:false;
                        }
                    }
                    if(!$business_selfscore && !$bcansetscore){
                        $product['scored_set'] = 0;
                    }
                }

				if($product['scored_set']==0){
					if($sysset['scoredkmaxpercent'] == 0){
						$scoremaxtype = 1;
						$scoredkmaxmoney += 0;
					}else{
						if($sysset['scoredkmaxpercent'] >= 0 && $sysset['scoredkmaxpercent']<100){
							$scoredkmaxmoney += $sysset['scoredkmaxpercent'] * 0.01 * $guige['sell_price'] * $sdata[2];
						}else{
							$scoredkmaxmoney += $guige['sell_price'] * $sdata[2];
						}
					}
				}elseif($product['scored_set']==1){
					$scoremaxtype = 1;
					$scoredkmaxmoney += $product['scored_val'] * 0.01 * $guige['sell_price'] * $sdata[2];
				}elseif($product['scored_set']==2){
					$scoremaxtype = 1;
					$scoredkmaxmoney += $product['scored_val'] * $sdata[2];
				}else{
					$scoremaxtype = 1;
					$scoredkmaxmoney += 0;
				}

                $pre_product_price = $guige['sell_price'] * $sdata[2];
                $product_price += $pre_product_price;
                if(getcustom('member_level_moneypay_price')){
                    $pre_product_price_cha = $pre_product_putongprice-$pre_product_price;//普通价格与会员购买价格的差额
                    $product_price_cha += $pre_product_price_cha;
                }
                $remark = $data['remark'][$key];
                $ogid = $data['ogid'][$key];
				$prolist[] = ['product'=>$product,'guige'=>$guige,'num'=>$sdata[2],'cartid'=>$cartid,'remark' => $remark??'','ogid' => $ogid];
				
				$proids[] = $product['id'];
				$cids = array_merge($cids,explode(',',$product['cid']));
				$givescore += $guige['givescore'] * $sdata[2];
			}
			//会员折扣
			$leveldk_money = 0;
			if($userlevel && $userlevel['discount']>0 && $userlevel['discount']<10){
				$leveldk_money = $needzkproduct_price * (1 - $userlevel['discount'] * 0.1);
			}
			$totalprice = $product_price;

            //满减活动，使用餐饮-促销
			$manjian_money = 0;
			$totalprice = $totalprice - $manjian_money;
			if($totalprice < 0) $totalprice = 0;
			//优惠券
			if($data['couponrid'] > 0){
                $coupontotal = $totalprice - $notcoupon_price;
				$couponrid = $data['couponrid'];
                $coupon_bid = [$data['bid'],'-1'];
                if(getcustom('restaurant_coupon_apply_business')){
                    if($data['bid'] > 0)$coupon_bid[]=0;
                }
				$couponrecord = Db::name('coupon_record')->where('bid','in',$coupon_bid)->where('aid',aid)->where('mid',mid)->where('id',$couponrid)->find();
				$coupon_type = [1,4,5];
                if(getcustom('restaurant_cashdesk_discount_coupon'))$coupon_type[] = 10;//折扣券
				if(!$couponrecord){
					return $this->json(['status'=>0,'msg'=>'该'.t('优惠券').'不存在']);
				}elseif($couponrecord['status']!=0){
					return $this->json(['status'=>0,'msg'=>'该'.t('优惠券').'已使用过了']);
				}elseif($couponrecord['starttime'] > time()){
					return $this->json(['status'=>0,'msg'=>'该'.t('优惠券').'尚未开始使用']);	
				}elseif($couponrecord['endtime'] < time()){
					return $this->json(['status'=>0,'msg'=>'该'.t('优惠券').'已过期']);	
				}elseif($couponrecord['minprice'] > $coupontotal){
					return $this->json(['status'=>0,'msg'=>'该'.t('优惠券').'不符合条件']);
				}elseif(!in_array($couponrecord['type'],$coupon_type)){
					return $this->json(['status'=>0,'msg'=>'该'.t('优惠券').'不符合条件']);
				}

				$couponinfo = Db::name('coupon')->where('aid',aid)->where('id',$couponrecord['couponid'])->find();
                if(empty($couponinfo)){
                    return $this->json(['status'=>0,'msg'=>'该'.t('优惠券').'不存在或已作废']);
                }
                if($couponinfo['fwscene']!==0){
                    return $this->json(['status'=>0,'msg'=>'该'.t('优惠券').'不符合使用条件']);
                }
                
				if($couponinfo['fwtype']==2){//指定菜品可用
					$productids = explode(',',$couponinfo['productids']);
					if(!array_intersect($proids,$productids)){
						return $this->json(['status'=>0,'msg'=>'该'.t('优惠券').'指定菜品可用']);
					}
                    $thistotalprice = 0;
                    foreach($prolist as $k2=>$v2){
                        $product = $v2['product'];
                        if(in_array($product['id'],$productids)){
                            $thistotal =  $v2['guige']['sell_price'] * $v2['num'];
                            if(getcustom('restaurant_product_package')){
                                 if($product['product_type'] ==2 && $product['package_is_coupon'] ==1){
                                     $cart = Db::name('restaurant_shop_cart')->where('id',$v2['cartid'])->find();
                                     $thistotal = $cart['package_price'] * $cart['num'];
                                 }
                            }
                            $thistotalprice += $thistotal;
                        }
                    }
                    if($thistotalprice < $couponinfo['minprice']){
                        return $this->json(['status'=>0,'msg'=>'该'.t('优惠券').'指定菜品未达到'.$couponinfo['minprice'].'元']);
                    }
                    $couponrecord['money'] = min($thistotalprice,$couponrecord['money']);
				}
				if($couponinfo['fwtype']==1){//指定类目可用
					$categoryids = explode(',',$couponinfo['categoryids']);
					$clist = Db::name('restaurant_product_category')->where('pid','in',$categoryids)->select()->toArray();
					foreach($clist as $kc=>$vc){
						$categoryids[] = $vc['id'];
						$cate2 = Db::name('restaurant_product_category')->where('pid',$vc['id'])->find();
						$categoryids[] = $cate2['id'];
					}
					if(!array_intersect($cids,$categoryids)){
						return $this->json(['status'=>0,'msg'=>'该'.t('优惠券').'指定分类可用']);
					}
                    $thistotalprice = 0;
                    foreach($prolist as $k2=>$v2){
                        $product = $v2['product'];
                        if(array_intersect(explode(',',$product['cid']),$categoryids)){
                            $thistotal =  $v2['guige']['sell_price'] * $v2['num'];
                            if(getcustom('restaurant_product_package')){
                                if($product['product_type'] ==2 && $product['package_is_coupon'] ==1){
                                    $cart = Db::name('restaurant_shop_cart')->where('id',$v2['cartid'])->find();
                                    $thistotal = $cart['package_price'] * $cart['num'];
                                }
                            }
                            $thistotalprice += $thistotal;
                        }
                    }
                    if($thistotalprice < $couponinfo['minprice']){
                        return $this->json(['status'=>0,'msg'=>'该'.t('优惠券').'指定分类未达到'.$couponinfo['minprice'].'元']);
                    }
                    $couponrecord['money'] = min($thistotalprice,$couponrecord['money']);
				}

                $recordupdata = ['status'=>1,'usetime'=>time()];
                if(getcustom('coupon_pack')){
                    //张数
                    if($couponrecord && $couponrecord['packrid'] && $couponrecord['num'] && $couponrecord['num']>0){
                        $usenum = $couponrecord['usenum']+1;
                        if($usenum<$couponrecord['num']){
                            $recordupdata = ['status'=>0,'usenum'=>$usenum];
                        }else{
                            $recordupdata = ['status'=>1,'usenum'=>$couponrecord['num'],'usetime'=>time()];
                        }
                    }
                }
                Db::name('coupon_record')->where('id',$couponrid)->update($recordupdata);
				if($couponrecord['type']==4){//运费抵扣券
					$coupon_money = 0;
				}if($couponrecord['type']==10){//折扣券
                    $coupon_money = $totalprice * (100- $couponrecord['discount']) * 0.01;
                }else{
					$coupon_money = $couponrecord['money'];
					if($coupon_money > $totalprice) $coupon_money = $totalprice;
				}
			}else{
				$coupon_money = 0;
			}
			//促销活动
			if($data['cuxiaoid'] > 0){
			   
			    $cuxiaototal = $totalprice - $notcuxiao_price;
				$cuxiaoid = $data['cuxiaoid'];
				$cuxiaoinfo = Db::name('restaurant_cuxiao')->where("bid=-1 or bid=".$data['bid'])->where('aid',aid)->where('id',$cuxiaoid)->find();
                if(getcustom('restaurant_cuxiao_activity_day')){
                    //促销活动日
                    if($cuxiaoinfo['activity_day_type'] ==0){//周几
                        $now_week = date('w');
                        $activity_day_week = explode(',',$cuxiaoinfo['activity_day_week']);
                        if(!in_array($now_week,$activity_day_week)){
                            return $this->json(['status'=>0,'msg'=>'非活动日，不可使用']);
                        }
                    }else{//几号
                        $now_date = date('d');
                        $activity_day_date = explode(',',$cuxiaoinfo['activity_day_week']);
                        if(!in_array($now_date,$activity_day_date)){
                            return $this->json(['status'=>0,'msg'=>'非活动日，不可使用']);
                        }
                    }
                }
                if(getcustom('restaurant_cuxiao_use_time_range')){
                    $now_time =strtotime(date('H:i:s'));
                    if($cuxiaoinfo['use_starttime'] && $cuxiaoinfo['use_endtime'] && ( $now_time < strtotime($cuxiaoinfo['use_starttime']) || $now_time > strtotime($cuxiaoinfo['use_endtime']))){
                        return $this->json(['status'=>0,'msg'=>'该促销在'.$cuxiaoinfo['use_starttime'].'-'.$cuxiaoinfo['use_endtime'].'可用']);
                    }
                }
                //多时间段
                if(getcustom('restaurant_cuxiao_multi_use_time_range')){
                    $multi_time_range = json_decode($cuxiaoinfo['multi_time_range'],true);
                    if($multi_time_range){
                        $now_time =strtotime(date('H:i'));
                        $is_rangetime = 0;
                        foreach($multi_time_range as $rangetime){
                            if( $now_time > strtotime($rangetime['starttime'])  && $now_time < strtotime($rangetime['endtime'])){
                                $is_rangetime =1;
                            }
                        }
                        if(!$is_rangetime) return $this->json(['status'=>0,'msg'=>'该促销不在可用时间段内']);
                    }
                }
				if(!$cuxiaoinfo){
					return $this->json(['status'=>0,'msg'=>'该促销活动不存在']);
				}elseif($cuxiaoinfo['starttime'] > time()){
					return $this->json(['status'=>0,'msg'=>'该促销活动尚未开始']);	
				}elseif($cuxiaoinfo['endtime'] < time()){
					return $this->json(['status'=>0,'msg'=>'该促销活动已结束']);	
				}elseif($cuxiaoinfo['type']!=5 && $cuxiaoinfo['type']!=6 && $cuxiaoinfo['type']!=7 && $cuxiaoinfo['minprice'] > $cuxiaototal){
					return $this->json(['status'=>0,'msg'=>'该促销活动不符合条件']);
				}elseif(($cuxiaoinfo['type']==5 || $cuxiaoinfo['type']==6) && $cuxiaoinfo['minnum'] > $totalnum){
					return $this->json(['status'=>0,'msg'=>'该促销活动不符合条件']);
				}
                if(getcustom('restaurant_first_pay_shop_canuse')){
                    //先付后吃，扫码点餐可用
                    if($table['pindan_status'] ==0 && $cuxiaoinfo['first_pay_shop_canuse'] ==0){
                        return $this->json(['status'=>0,'msg'=>'扫码点餐不可用']);
                    }
                }
                $cuxiao_product_total = 0; //算折扣时，重新计算非打折的商品的金额
				if($cuxiaoinfo['fwtype']==2){//指定菜品可用
					$productids = explode(',',$cuxiaoinfo['productids']);
					if(!array_intersect($proids,$productids)){
						return $this->json(['status'=>0,'msg'=>'该促销活动指定菜品可用']);
					}
                    //type ==5本来不放在这判断，但是需要计算 需要打折的商品总价，所以放在这里，下面判断金额加限制
                    if($cuxiaoinfo['type']==1 || $cuxiaoinfo['type']==2 || $cuxiaoinfo['type']==3 || $cuxiaoinfo['type']==4 || $cuxiaoinfo['type']==5){//指定菜品是否达到金额要求
                        //判断金额是否满足
                        $needzkproduct_price = 0;//当前参与促销后，不能参与的折扣 金额总价
                        foreach($prolist as $vpro){
                            if(in_array($vpro['product']['id'], $productids)){
                                $this_cuxiao_product_total =$vpro['guige']['sell_price'] * $vpro['num'];
                                if(getcustom('restaurant_product_package')){
                                    if($vpro['product']['product_type'] ==2 && $vpro['product']['package_is_cuxiao'] ==1){
                                        $cart = Db::name('restaurant_shop_cart')->where('id',$vpro['cartid'])->find();
                                        $this_cuxiao_product_total = $cart['package_price'] * $cart['num'];
                                    }
                                }
                                $cuxiao_product_total += $this_cuxiao_product_total;
                                $is_add_zkprice = 1;//是否计算打折扣金额中
                                if(getcustom('restaurant_product_not_member_discount')){
                                    if(!$vpro['product']['join_member_disount'])$is_add_zkprice=0;//不参与会员折扣
                                }
                                if($is_add_zkprice && $vpro['product']['lvprice']==0){ //未开启会员价
                                    $needzkproduct_price += $this_cuxiao_product_total;
                                }
                            }
                        }
                        $cuxiao_leveldk_money = $needzkproduct_price *(1 - $userlevel['discount'] * 0.1);
                        if($cuxiao_leveldk_money >0){
                            //禁止折上折
                            $leveldk_money = $leveldk_money - $cuxiao_leveldk_money;
                            $leveldk_money = $leveldk_money <=0?0: $leveldk_money;
                        }
                        //type=5是满件，所以不判断最小金额
                        if($cuxiao_product_total < $cuxiaoinfo['minprice'] && $cuxiaoinfo['type'] !=5){
                            return $this->json(['status'=>0,'msg'=>$cuxiaoinfo['name'].'指定菜品总价未达到'.$cuxiaoinfo['minprice'].'元']);
                        }
                    }
                    if($cuxiaoinfo['type']==6 || $cuxiaoinfo['type']==5){//指定菜品是否达到件数要求
                        $thistotalnum = 0;
                        foreach($prolist as $vpro){
                            if(in_array($vpro['product']['id'], $productids)){
                                $thistotalnum += $vpro['num'];
                            }
                        }
                        if($thistotalnum < $cuxiaoinfo['minnum']){
                            return $this->json(['status'=>0,'msg'=>$cuxiaoinfo['name'].'指定菜品总数未达到'.$cuxiaoinfo['minnum'].'件']);
                        }
                    }
				}
				if($cuxiaoinfo['fwtype']==1){//指定类目可用
					$categoryids = explode(',',$cuxiaoinfo['categoryids']);
					$clist = Db::name('restaurant_product_category')->where('pid','in',$categoryids)->select()->toArray();
					foreach($clist as $kc=>$vc){
						$categoryids[] = $vc['id'];
						$cate2 = Db::name('restaurant_product_category')->where('pid',$vc['id'])->find();
						$categoryids[] = $cate2['id'];
					}
					if(!array_intersect($cids,$categoryids)){
						return $this->json(['status'=>0,'msg'=>'该促销活动指定分类可用']);
					}
                    if($cuxiaoinfo['type']==1 || $cuxiaoinfo['type']==2 || $cuxiaoinfo['type']==3 || $cuxiaoinfo['type']==4){//指定菜品是否达到金额要求
                        $needzkproduct_price = 0;//当前参与促销后，不能参与的折扣 金额总价
                        foreach($prolist as $vpro){
                            $cuxiao_pro_cidArr = explode(',',$vpro['product']['cid']);
                            if(array_intersect($cuxiao_pro_cidArr, $categoryids)){
                                $this_cuxiao_cate_total =  $vpro['guige']['sell_price'] * $vpro['num'];
                                $cuxiao_product_total += $this_cuxiao_cate_total;
                                
                                if(getcustom('restaurant_product_package')){
                                    if($vpro['product']['product_type'] ==2 && $vpro['product']['package_is_cuxiao'] ==1){
                                        $cart = Db::name('restaurant_shop_cart')->where('id',$vpro['cartid'])->find();
                                        $this_cuxiao_cate_total = $cart['package_price'] * $cart['num'];
                                    }
                                }
                                $is_add_zkprice = 1;//是否计算打折扣金额中
                                if(getcustom('restaurant_product_not_member_discount')){
                                    if(!$vpro['product']['join_member_disount'])$is_add_zkprice=0;//不参与会员折扣
                                }
                                if($is_add_zkprice && $vpro['product']['lvprice']==0){ //未开启会员价
                                    $needzkproduct_price += $this_cuxiao_cate_total;
                                }
                            }
                        }
                        $cuxiao_leveldk_money = $needzkproduct_price *(1 - $userlevel['discount'] * 0.1);
                        if($cuxiao_leveldk_money >0){
                            //禁止折上折
                            $leveldk_money = $leveldk_money - $cuxiao_leveldk_money;
                            $leveldk_money = $leveldk_money <=0?0: $leveldk_money;
                        }
                        if($cuxiao_product_total < $cuxiaoinfo['minprice']){
                            return $this->json(['status'=>0,'msg'=>$cuxiaoinfo['name'].'指定类目总价未达到'.$cuxiaoinfo['minprice'].'元']);
                        }
                    }
                    if($cuxiaoinfo['type']==6 || $cuxiaoinfo['type']==5){//指定类目内菜品是否达到件数要求
                        $thistotalnum = 0;
                        foreach($prolist as $vpro){
                            $cuxiao_pro_cidArr = explode(',',$vpro['product']['cid']);
                            if(array_intersect($cuxiao_pro_cidArr, $categoryids)){
                                $thistotalnum += $vpro['num'];
                            }
                        }
                        if($thistotalnum < $cuxiaoinfo['minnum']){
                            return $this->json(['status'=>0,'msg'=>$cuxiaoinfo['name'].'指定分类总数未达到'.$cuxiaoinfo['minnum'].'件']);
                        }
                    }
				}
                if($cuxiaoinfo['fwtype']==0){
                    $needzkproduct_price = 0;//当前参与促销后，不能参与的折扣 金额总价
                    foreach($prolist as $vpro){
                        $cuxiao_product_total += $vpro['guige']['sell_price'] * $vpro['num'];
                        $is_add_zkprice = 1;//是否计算打折扣金额中
                        if (getcustom('restaurant_product_not_member_discount')) {
                            if (!$vpro['product']['join_member_disount']) $is_add_zkprice = 0;//不参与会员折扣
                        }
                        if ($is_add_zkprice && $vpro['product']['lvprice'] == 0) { //未开启会员价
                            $needzkproduct_price += $cuxiao_product_total;
                        }
                    }

                    $cuxiao_leveldk_money = $needzkproduct_price *(1 - $userlevel['discount'] * 0.1);
                    if($cuxiao_leveldk_money >0){
                        //禁止折上折
                        $leveldk_money = $leveldk_money - $cuxiao_leveldk_money;
                        $leveldk_money = $leveldk_money <=0?0: $leveldk_money;
                    }
                }
				if($cuxiaoinfo['type']==1 || $cuxiaoinfo['type']==6){//满额立减 满件立减
					$manjian_money = $manjian_money + $cuxiaoinfo['money'];
					$cuxiaomoney = $cuxiaoinfo['money'] * -1;
				}elseif($cuxiaoinfo['type']==2){//满额赠送
					$cuxiaomoney = 0;
					$product = Db::name('restaurant_product')->where('aid',aid)->where('id',$cuxiaoinfo['proid'])->find();
					$guige = Db::name('restaurant_product_guige')->where('aid',aid)->where('id',$cuxiaoinfo['ggid'])->find();
					if(!$product) return $this->json(['status'=>0,'msg'=>'赠送产品不存在']);
					if(!$guige) return $this->json(['status'=>0,'msg'=>'赠送产品规格不存在']);
					if($guige['stock'] < 1){
						return $this->json(['status'=>0,'msg'=>'赠送产品库存不足']);
					}
					$prolist[] = ['product'=>$product,'guige'=>$guige,'num'=>1,'isSeckill'=>0];
				}elseif($cuxiaoinfo['type']==3){//加价换购
					$cuxiaomoney = $cuxiaoinfo['money'];
					$product = Db::name('restaurant_product')->where('aid',aid)->where('id',$cuxiaoinfo['proid'])->find();
					$guige = Db::name('restaurant_product_guige')->where('aid',aid)->where('id',$cuxiaoinfo['ggid'])->find();
					if(!$product) return $this->json(['status'=>0,'msg'=>'换购产品不存在']);
					if(!$guige) return $this->json(['status'=>0,'msg'=>'换购产品规格不存在']);
					if($guige['stock'] < 1){
						return $this->json(['status'=>0,'msg'=>'换购产品库存不足']);
					}
					$prolist[] = ['product'=>$product,'guige'=>$guige,'num'=>1,'isSeckill'=>0];
				}elseif($cuxiaoinfo['type']==4 || $cuxiaoinfo['type']==5){//满额打折 满件打折
					$cuxiaomoney = $cuxiao_product_total * (1 - $cuxiaoinfo['zhekou'] * 0.1);
					$manjian_money = $manjian_money + $cuxiaomoney;
					$cuxiaomoney = $cuxiaomoney * -1;
				}elseif($cuxiaoinfo['type']==7){
                    if(getcustom('restaurant_the_second_discount')){
                        $this_cuxiao_money = 0;
                        if($cuxiaoinfo['is_one_product'] ==1){//同一件 
                            foreach ($prolist as $product) {
                                if(getcustom('restaurant_product_package')){
                                    if($product['product']['package_is_cuxiao'] ==0 && $product['product']['product_type'] ==2){
                                         continue;
                                    }
                                    if($product['product']['product_type'] ==2){
                                        $cartdata = Db::name('restaurant_shop_cart')->where('id',$product['cartid'])->find();
                                        $product['guige']['sell_price'] =  $cartdata['package_price'];
                                    }
                                }
                                if($product['num'] >1){
                                    $this_cuxiao_money +=  $product['guige']['sell_price'] * (1 - $cuxiaoinfo['zhekou'] * 0.1);
                                }
                            }
                        }else{
                            //查找最低价格,未计算加料
                                $this_min_money = 0;
                            foreach ($prolist as $product) {
                                if(getcustom('restaurant_product_package')){
                                    if($product['product']['package_is_cuxiao'] ==0 && $product['product']['product_type'] ==2){
                                        continue;
                                    }
                                    if($product['product']['product_type'] ==2){
                                       $cartdata = Db::name('restaurant_shop_cart')->where('id',$product['cartid'])->find();
                                        $product['guige']['sell_price'] =  $cartdata['package_price'];
                                    }
                                }
                                if($product['guige']['sell_price'] < $this_min_money || $this_min_money == 0 ){
                                    $this_min_money = $product['guige']['sell_price'];
                                }
                            }

                            $this_cuxiao_money=  $this_min_money * (1 - $cuxiaoinfo['zhekou'] * 0.1);
                        }
                        $cuxiaomoney = $this_cuxiao_money* -1;
                    }

                }else{
					$cuxiaomoney = 0;
				}
			}else{
				$cuxiaomoney = 0;
			}

            $totalprice = $totalprice - $coupon_money + $cuxiaomoney   -$leveldk_money;
	
			$tea_fee = ($shop_set['tea_fee_status']==1 && $shop_set['tea_fee']>0 ? $shop_set['tea_fee'] * $data['renshu'] : 0);
			$totalprice = $totalprice + $tea_fee;

			//积分抵扣
			$scoredkscore = 0;
			$scoredk_money = 0;
			if($post['usescore']==1){
				$adminset = Db::name('admin_set')->where('aid',aid)->find();
				$score2money = $adminset['score2money'];
				$scoredkmaxpercent = $adminset['scoredkmaxpercent'];
                if(getcustom('sysset_scoredkmaxpercent_memberset')){
                    //处理会员单独设置积分最大抵扣比例
                    $scoredkmaxpercent = $adminset['scoredkmaxpercent'] = \app\custom\ScoredkmaxpercentMemberset::dealmemberscoredk(aid,$this->member,$scoredkmaxpercent);
                }
				$scorebdkyf = $adminset['scorebdkyf'];
				$scoredk_money = $this->member['score'] * $score2money;
				if($scorebdkyf == 1){//积分不抵扣运费
					if($scoredk_money > $totalprice - $freight_price) $scoredk_money = $totalprice - $freight_price;
				}else{
					if($scoredk_money > $totalprice) $scoredk_money = $totalprice;
				}
				if($scoremaxtype == 0){
					if($scoredkmaxpercent >= 0 && $scoredkmaxpercent < 100 && $scoredk_money > 0 && $scoredk_money > $totalprice * $scoredkmaxpercent * 0.01){
						$scoredk_money = $totalprice * $scoredkmaxpercent * 0.01;
					}
				}else{
					if($scoredk_money > $scoredkmaxmoney) $scoredk_money = $scoredkmaxmoney;
				}
				$totalprice = $totalprice - $scoredk_money;
				$totalprice = round($totalprice*100)/100;
				if($scoredk_money > 0){
					$scoredkscore = intval($scoredk_money / $score2money);
				}
			}

            Log::write([
                'file'=>__FILE__.__LINE__,
                '餐饮点餐订单编辑,orderid：'=>$table['orderid'],
                'post'=>json_encode(input('post.')),
                'mid'=>mid
            ]);

			$orderdata = [];
//			dump($table);
//            if(!$table['orderid']) {
                $orderdata['aid'] = aid;
                //因手机端后台下单后，给加菜时，会被更新为 管理员的mid
                if($post['frompage'] != 'admin'){
                    $orderdata['mid'] =  mid;
                }         
                $orderdata['bid'] = $data['bid'];
                $orderdata['tableid'] = input('param.tableid');
//            }
			if(count($buydata) > 1){
				$orderdata['ordernum'] = $ordernum.'_'.$i;
			}else{
				$orderdata['ordernum'] = $ordernum;
			}
			$orderdata['title'] = $title.(count($prodata)>1?'等':'');
			
//			$orderdata['linkman'] = $address['name'];
//			$orderdata['tel'] = $address['tel'];
//			$orderdata['area'] = $address['area'];
//			$orderdata['address'] = $address['address'];
//			$orderdata['longitude'] = $address['longitude'];
//			$orderdata['latitude'] = $address['latitude'];
//			$orderdata['area2'] = $address['province'].','.$address['city'].','.$address['district'];
			$orderdata['totalprice'] = $totalprice;
			$orderdata['product_price'] = $product_price;
			$orderdata['renshu'] = $data['renshu'];
			$orderdata['tea_fee'] = $tea_fee;
			$orderdata['leveldk_money'] = $leveldk_money;  //会员折扣
			$orderdata['manjian_money'] = $manjian_money;	//满减活动
			$orderdata['scoredk_money'] = $scoredk_money;	//积分抵扣
			$orderdata['coupon_money'] = $coupon_money;		//优惠券抵扣
			$orderdata['scoredkscore'] = $scoredkscore;	//抵扣掉的积分
            $orderdata['cuxiao_money'] = abs($cuxiaomoney);
            $orderdata['cuxiao_ids'] = $cuxiaoid;
			$orderdata['coupon_rid'] = $couponrid;
			$orderdata['freight_price'] = $freight_price; //运费
            if($orderdata['bid'] ==0){
                $orderdata['givescore'] = $givescore;
            }
		
			$orderdata['message'] = $data['message'];
			if($eattype ==0){
                $orderdata['createtime'] = time();
            }
			$orderdata['platform'] = platform;
			$orderdata['hexiao_code'] = random(16);
			$orderdata['hexiao_qr'] = createqrcode(m_url('admin/hexiao/hexiao?type=restaurant_shop&co='.$orderdata['hexiao_code']));
			$orderdata['field1'] = $data['field1'];
			$orderdata['field2'] = $data['field2'];
			$orderdata['field3'] = $data['field3'];
			$orderdata['field4'] = $data['field4'];
			$orderdata['field5'] = $data['field5'];
			if(getcustom('restaurant_take_food')){
			   $restaurant_take_food_sysset = Db::name('restaurant_take_food_sysset')->where('aid',aid)->where('bid',$data['bid'])->find();
			   if($restaurant_take_food_sysset['status'] ==1){
                   $taday_start =  strtotime(date('Y-m-d 00:00:01'));
                   $taday_end =  $taday_start + 86399;
                   $today_ordernum = 0+Db::name('restaurant_shop_order')
                           ->where('aid',aid)->where('bid',$data['bid'])
                           ->where('createtime','between',[$taday_start,$taday_end])
                           ->count();
                   $today_ordernum = $shop_set['start_pickup_number'] + $today_ordernum;
                   $today_ordernum = $today_ordernum==0?1:$today_ordernum;
                   if($today_ordernum < 10 ){
                       $today_ordernum ='00'.$today_ordernum;
                   }elseif ($today_ordernum >= 10 && $today_ordernum < 100){
                       $today_ordernum ='0'.$today_ordernum;
                   }
                   $orderdata['pickup_number'] = $shop_set['take_food_number_prefix'].$today_ordernum;
               }
            }
            if(getcustom('restaurant_bar_table_order')){
                $orderdata['is_bar_table_order'] = $is_bar_table;
                $mdid = input('param.mdid',0);
                if($mdid){
                    //门店信息
                    $orderdata['mdid'] = $mdid;
                }
            }
            if(getcustom('restaurant_table_timing')){
                if($table['timing_fee_type'] >0){
                    $orderdata['timeing_start'] = strtotime(date('Y-m-d H:i',time()));
                }
            }
            if(getcustom('restaurant_table_minprice')){
                $service_money = 0;
                $service_totalprice =  $totalprice;
                if($table){
                    if($table['minprice'] > 0 && $service_totalprice < $table['minprice']){
                        //计算服务费
                        if($table['service_fee_type'] ==0){
                            $service_money = $table['service_fee'];
                        }
                        if($table['service_fee_type'] ==1){
                            $service_money = $table['service_fee']/100 * $service_totalprice;
                        }
                    }
                }
                $totalprice +=$service_money;
                $orderdata['totalprice'] = $totalprice;
                $orderdata['service_money'] = $service_money;
            }
            if(getcustom('extend_qrcode_variable_fenzhang')){
                $orderdata['qrcode_val_code'] = input('param.fzcode');
            }
            // 预定可点餐
            if(getcustom('restaurant_book_order')){
                $orderdata['isbook'] = input('param.isbook');
                $orderdata['bookid'] = input('param.bookid');
            }

            if(getcustom('member_level_moneypay_price')){
                $product_putongprice = $product_price + $product_price_cha;
                $orderdata['product_putongprice'] = $product_putongprice && $product_putongprice>0?$product_putongprice:0;//商品普通价格
                $totalputongprice = $totalprice + $product_price_cha;
                $orderdata['totalputongprice'] = $totalputongprice && $totalputongprice>0?$totalputongprice:0;//普通价格总价
            }
			if(($table['orderid'] &&  $post['frompage'] == 'admin') ||($table['orderid'] && $eattype ==1)) {
                $orderdata['settle_status'] =1;//20250526新增，解决重复使用优惠问题
                Db::name('restaurant_shop_order')->where('id', $table['orderid'])->update($orderdata);
                $orderid = $table['orderid'];
            } else {
                $orderid = Db::name('restaurant_shop_order')->insertGetId($orderdata);
            }
            $orderdata = Db::name('restaurant_shop_order')->where('id', $orderid)->find();
            if(!$orderdata){
            	 return $this->json(['status'=>0,'msg'=>'下单失败']);
            }

            $payparams = [];//payorder表额外参数
            if(getcustom('member_level_moneypay_price')){
                $payparams['putongprice'] = $orderdata['totalputongprice'] && $orderdata['totalputongprice']>0?$orderdata['totalputongprice']:0;//所有商品普通价格总价
            }
			$payorderid = \app\model\Payorder::createorder(aid,$orderdata['bid'],$orderdata['mid'],'restaurant_shop',$orderid,$orderdata['ordernum'],$orderdata['title'],$orderdata['totalprice'],$orderdata['scoredkscore'],0,$payparams);
            //更新餐桌状态
            $is_update_table = true;
            if(getcustom('restaurant_shop_pinzhuo')) {
                //如果开启拼桌，不更新桌台的订单
                $pinzhuo_status =  Db::name('restaurant_table')->where('aid', aid)->where('id', $table['id'])->value('pinzhuo_status');
                if($pinzhuo_status ==1)$is_update_table = false;
            }
            // 预约点餐，不更新桌台的订单
            if(getcustom('restaurant_book_order') && input('param.isbook') == 1 && input('param.bookid') > 0){
                $is_update_table = false;
            }
            if($is_update_table){
                Db::name('restaurant_table')->where('aid', aid)->where('id', $table['id'])->update(['status' => 2, 'orderid' => $orderid]);
            }
           
			$alltotalprice += $orderdata['totalprice'];
			$alltotalscore += $orderdata['scoredkscore'];
            if(getcustom('member_level_moneypay_price')){
                $alltotalputongprice += $orderdata['totalputongprice'];//所有商品普通价格总价
            }
			
			$istc1 = 0; //设置了按单固定提成时 只将佣金计算到第一个菜品里
            $istc2 = 0;
            $istc3 = 0;
            $njlprice = 0;
            $njltitle = '';
			foreach($prolist as $key=>$v){
				$product = $v['product'];
				$guige = $v['guige'];
				$num = $v['num'];
				if(getcustom('product_jialiao')){
                    $cardata = Db::name('restaurant_shop_cart')->where('aid',aid)->where('mid',mid)->where('ggid',$guige['id'])->where('proid',$product['id'])->find();
                    $input_jldata =   urldecode(input('jldata'));
                    if( $input_jldata && input('btype') ==1 ){
                        $jlstring = explode('-',$input_jldata);
                        $cardata['jlprice'] =  $jlstring[0];
                        $cardata['jltitle'] =  $jlstring[1];
                    }
                }
                $ogid = $v['ogid'];//当前的ordergoodsid
                $ordergoodsdata = [];
                if($ogid){
                    $ordergoodsdata = Db::name('restaurant_shop_order_goods')->where('aid',aid)->where('id',$ogid)->find();
                }
                if(getcustom('restaurant_product_jialiao')){
                    //如果商品设置打折
                    $cartid  =  $v['cartid'];//购物车
                    if($cartid){
                        $jldata = Db::name('restaurant_shop_cart')->where('id',$cartid)->value('jldata');
                      
                        $njlprice = 0;
                        $njltitle = '';
                        if($jldata){
                            $njldata = json_decode($jldata,true);
                            foreach($njldata as $key=>$val){
                                $njlprice += $val['num'] * $val['price'];
                                $njltitle .=$val['title'].'*'.$val['num'].'/';
                            }
                            $njltitle = rtrim($njltitle,'/');
                        }
                    }else{
                        $njlprice= $ordergoodsdata['njlprice'];
                        $njltitle = $ordergoodsdata['njltitle'];
                    }
                }
				$ogdata = [];
				$ogdata['aid'] = aid;
				$ogdata['bid'] = $product['bid'];
				$ogdata['mid'] = mid;
				$ogdata['orderid'] = $orderid;
				$ogdata['ordernum'] = $orderdata['ordernum'];
				$ogdata['proid'] = $product['id'];
				$ogdata['name'] = $product['name'];
				$ogdata['pic'] = $guige['pic'] ? $guige['pic'] : $product['pic'];
				$ogdata['procode'] = $product['procode'];
				$ogdata['ggid'] = $guige['id'];
				$ogdata['ggname'] = $guige['name'];
				if(getcustom('restaurant_product_package')){
                    $ogdata['product_type'] = $product['product_type'];
                }
				//$ogdata['cid'] = $product['cid'];
				$ogdata['num'] = $num;
                $ogdata['remark'] = $v['remark'];
				$ogdata['cost_price'] = $guige['cost_price'];
				$sell_price =  $guige['sell_price'];
				if(getcustom('restaurant_product_package')){
                    $cartdata = Db::name('restaurant_shop_cart')->where('id',$v['cartid'])->find();
                    if($cartdata){
                        $ogdata['package_data'] = $cartdata['package_data']; 
                        $ogdata['is_package'] = 1; 
                    }
                }
				$ogdata['sell_price'] = $sell_price;
				$ogdata['status'] = 0;
				if($eattype ==0){
                    $ogdata['createtime'] = time();
                }
                $og_totalprice = $num * $sell_price;
                if(getcustom('member_level_moneypay_price')){
                    $ogdata['sell_putongprice'] = $guige['sell_putongprice'];//商品普通价格
                    $totalputongprice2 = $num * $guige['sell_putongprice'];
                    $ogdata['totalputongprice'] = $totalputongprice2 && $totalputongprice2>0?$totalputongprice2:0;//普通价格总价
                }

				if(getcustom('product_jialiao')){
				    if($cardata){
                        $og_totalprice = bcadd($og_totalprice,$cardata?$cardata['jlprice']:0,2);
                        $ogdata['jlprice'] = $cardata['jlprice']?$cardata['jlprice']:0;
                        $ogdata['jltitle'] = $cardata['jltitle']?$cardata['jltitle']:'';
                        if(getcustom('member_level_moneypay_price')){
                            $ogdata['totalputongprice'] = bcadd($totalputongprice2,$cardata?$cardata['jlprice']:0,2);//普通价格总价
                        }
                    }
                }
                $ogdata['totalprice'] =$og_totalprice;
                
                if(getcustom('restaurant_product_jialiao')){
                    if($njlprice){
                        $ogdata['njlprice'] = $njlprice;
                        $ogdata['njltitle'] = $njltitle;
                        $ogdata['totalprice'] = dd_money_format($num * $guige['sell_price'] + $njlprice * $num );
                    }
                    if(getcustom('member_level_moneypay_price')){
                        $ogdata['totalputongprice'] = dd_money_format($num * $guige['sell_putongprice'] + $njlprice * $num );//普通价格总价
                    }
                }

					//计算菜品实际金额  菜品金额 - 会员折扣 - 积分抵扣 - 满减抵扣 - 优惠券抵扣
					if($sysset['fxjiesuantype'] == 1 || $sysset['fxjiesuantype'] == 2){
						$allproduct_price = $product_price;
						$og_leveldk_money = 0;
						$og_coupon_money = 0;
						$og_scoredk_money = 0;
						$og_manjian_money = 0;
						if($allproduct_price > 0 && $og_totalprice > 0){
							if($leveldk_money){
								$og_leveldk_money = $og_totalprice / $allproduct_price * $leveldk_money;
							}
							if($coupon_money){
								$og_coupon_money = $og_totalprice / $allproduct_price * $coupon_money;
							}
							if($scoredk_money){
								$og_scoredk_money = $og_totalprice / $allproduct_price * $scoredk_money;
							}
							if($manjian_money){
								$og_manjian_money = $og_totalprice / $allproduct_price * $manjian_money;
							}
						}
						$og_totalprice = round($og_totalprice - $og_leveldk_money - $og_coupon_money - $og_scoredk_money - $og_manjian_money,2);
						if($og_totalprice < 0) $og_totalprice = 0;
					}
					if(getcustom('product_jialiao')){
                        $og_totalprice = bcadd($og_totalprice,$cardata['jlprice']?$cardata['jlprice']:0,2);
                    }
					if(getcustom('restaurant_product_jialiao')){
                        $og_totalprice  = dd_money_format($og_totalprice+$njlprice);
                    }
					$ogdata['real_totalprice'] = $og_totalprice; //实际菜品销售金额
                    Log::write([
                        'file'=>__FILE__.__LINE__,
                        'real_totalprice：'=>$og_totalprice,
                        'mid'=>mid
                    ]);
					
					//计算佣金的菜品金额
					$commission_totalprice = $ogdata['totalprice']; 
					if($sysset['fxjiesuantype'] == 1){ //按成交价格
						$commission_totalprice = $ogdata['real_totalprice'];
                        if($commission_totalprice < 0) $commission_totalprice = 0;
					}
					if($sysset['fxjiesuantype']==2){ //按利润提成
						$commission_totalprice = $ogdata['real_totalprice'] - $guige['cost_price'] * $num;
						if($commission_totalprice < 0) $commission_totalprice = 0;
					}
                    if($commission_totalprice < 0) $commission_totalprice = 0;

					$agleveldata = Db::name('member_level')->where('aid',aid)->where('id',$this->member['levelid'])->find();
					if($agleveldata['can_agent'] > 0 && $agleveldata['commission1own']==1){
						$this->member['pid'] = mid;
					}
					if($product['commissionset']!=-1){
                        if($this->member['pid']){
                            $parent1 = \app\custom\Restaurant::getParentWithLevel(aid, $this->member['pid']);
                            if($parent1 && $parent1['levelData']['can_agent'] != 0){
                                $ogdata['parent1'] = $parent1['id'];
                            }
                        }
                        if($parent1['pid']){
                            $parent2 = \app\custom\Restaurant::getParentWithLevel(aid, $parent1['pid']);
                            if($parent2 && $parent2['levelData']['can_agent'] > 1){
                                $ogdata['parent2'] = $parent2['id'];
                            }
                        }
                        if($parent2['pid']){
                            $parent3 = \app\custom\Restaurant::getParentWithLevel(aid, $parent2['pid']);
                            if($parent3 && $parent3['levelData']['can_agent'] > 2){
                                $ogdata['parent3'] = $parent3['id'];
                            }
                        }
                        if($product['commissionset']==1){//按菜品设置的分销比例
                            $commissiondata = json_decode($product['commissiondata1'],true);
                            if($commissiondata){
                                if($ogdata['parent1']) $ogdata['parent1commission'] = $commissiondata[$parent1['levelData']['id']]['commission1'] * $commission_totalprice * 0.01;
                                if($ogdata['parent2']) $ogdata['parent2commission'] = $commissiondata[$parent2['levelData']['id']]['commission2'] * $commission_totalprice * 0.01;
                                if($ogdata['parent3']) $ogdata['parent3commission'] = $commissiondata[$parent3['levelData']['id']]['commission3'] * $commission_totalprice * 0.01;
                            }
                        }elseif($product['commissionset']==2){//按固定金额
                            $commissiondata = json_decode($product['commissiondata2'],true);
                            if($commissiondata){
                                if($ogdata['parent1']) $ogdata['parent1commission'] = $commissiondata[$parent1['levelData']['id']]['commission1'] * $num;
                                if($ogdata['parent2']) $ogdata['parent2commission'] = $commissiondata[$parent2['levelData']['id']]['commission2'] * $num;
                                if($ogdata['parent3']) $ogdata['parent3commission'] = $commissiondata[$parent3['levelData']['id']]['commission3'] * $num;
                            }
                        }elseif($product['commissionset']==3){//提成是积分
                            $commissiondata = json_decode($product['commissiondata3'],true);
                            if($commissiondata){
                                if($ogdata['parent1']) $ogdata['parent1score'] = $commissiondata[$parent1['levelData']['id']]['commission1'] * $num;
                                if($ogdata['parent2']) $ogdata['parent2score'] = $commissiondata[$parent2['levelData']['id']]['commission2'] * $num;
                                if($ogdata['parent3']) $ogdata['parent3score'] = $commissiondata[$parent3['levelData']['id']]['commission3'] * $num;
                            }
                        }else{ //按会员等级设置的分销比例
                            if($ogdata['parent1']){
                                if($parent1['levelData']['commissiontype']==1){ //固定金额按单
                                    if($istc1==0){
                                        $ogdata['parent1commission'] = $parent1['levelData']['commission1'];
                                        $istc1 = 1;
                                    }
                                }else{
                                    $ogdata['parent1commission'] = $parent1['levelData']['commission1'] * $commission_totalprice * 0.01;
                                }
                            }
                            if($ogdata['parent2']){
                                if($parent2['levelData']['commissiontype']==1){
                                    if($istc2==0){
                                        $ogdata['parent2commission'] = $parent2['levelData']['commission2'];
                                        $istc2 = 1;
                                    }
                                }else{
                                    $ogdata['parent2commission'] = $parent2['levelData']['commission2'] * $commission_totalprice * 0.01;
                                }
                            }
                            if($ogdata['parent3']){
                                if($parent3['levelData']['commissiontype']==1){
                                    if($istc3==0){
                                        $ogdata['parent3commission'] = $parent3['levelData']['commission3'];
                                        $istc3 = 1;
                                    }
                                }else{
                                    $ogdata['parent3commission'] = $parent3['levelData']['commission3'] * $commission_totalprice * 0.01;
                                }
                            }
                        }
					}
//                if(getcustom('restaurant_shop_pindan')){
//                    if($table['pindan_status'] ==1){
//                        $ogdata['times'] =1;
//                    }
//                }               		
                if($v['ogid']){
                    Db::name('restaurant_shop_order_goods')->where('id',$v['ogid'])->update($ogdata);
                    $ogid = $v['ogid'];
                }else{
                    $ogid = Db::name('restaurant_shop_order_goods')->insertGetId($ogdata);
                }
                $ogids[] = $ogid;
				if($ogdata['parent1'] && ($ogdata['parent1commission'] > 0 || $ogdata['parent1score'] > 0)){
					Db::name('member_commission_record')->insert(['aid'=>aid,'mid'=>$ogdata['parent1'],'frommid'=>mid,'orderid'=>$orderid,'ogid'=>$ogid,'type'=>'restaurant_shop','commission'=>$ogdata['parent1commission'],'score'=>$ogdata['parent1score'],'remark'=>'下级购买菜品奖励','createtime'=>time()]);
				}
				if($ogdata['parent2'] && ($ogdata['parent2commission'] || $ogdata['parent2score'])){
					Db::name('member_commission_record')->insert(['aid'=>aid,'mid'=>$ogdata['parent2'],'frommid'=>mid,'orderid'=>$orderid,'ogid'=>$ogid,'type'=>'restaurant_shop','commission'=>$ogdata['parent2commission'],'score'=>$ogdata['parent2score'],'remark'=>'下二级购买菜品奖励','createtime'=>time()]);
				}
				if($ogdata['parent3'] && ($ogdata['parent3commission'] || $ogdata['parent3score'])){
					Db::name('member_commission_record')->insert(['aid'=>aid,'mid'=>$ogdata['parent3'],'frommid'=>mid,'orderid'=>$orderid,'ogid'=>$ogid,'type'=>'restaurant_shop','commission'=>$ogdata['parent3commission'],'score'=>$ogdata['parent3score'],'remark'=>'下三级购买菜品奖励','createtime'=>time()]);
				}
	            
				//删除购物车
                if(input('btype') ==0 && $guige['id']){
                    $is_use_mid =1;
                    $cartwhere = [];
                    $cartwhere[] =['ggid','=',$guige['id']];
                    $cartwhere[] =['proid','=',$guige['product_id']];
                    if(getcustom('restaurant_shop_pindan')){
                        if($table['pindan_status'] ==1){
                            $is_use_mid = 0;
                            $cartwhere[] = ['tableid','=',$table['id']]; 
                        }
                    }
                    if($is_use_mid){
                        $cartwhere[] =['mid' ,'=', mid];
                    }
                    Db::name('restaurant_shop_cart')->where($cartwhere)->delete();
                }
				Db::name('restaurant_product_guige')->where('aid',aid)->where('id',$guige['id'])->update(['stock'=>Db::raw("stock-$num"),'sales'=>Db::raw("sales+$num"),'sales_daily'=>Db::raw("sales_daily+$num")]);
				Db::name('restaurant_product')->where('aid',aid)->where('id',$product['id'])->update(['stock'=>Db::raw("stock-$num"),'sales'=>Db::raw("sales+$num"),'sales_daily'=>Db::raw("sales_daily+$num")]);
                if(getcustom('restaurant_product_stock_daily')) {
                    if ($product['total_stock_daily_real'] > 0) {
                        Db::name('restaurant_product')->where('aid', aid)->where('id', $product['id'])->update(['total_stock_daily_real' => Db::raw("total_stock_daily_real-$num")]);
                    }
                }
				if(getcustom('restaurant_product_package')){
                    if($cartdata){
                        $package_data = $cartdata['package_data'] ;
                    }else{
                        $package_data = $orderdata['package_data'] ;
                    }
                    if($package_data){
                        $packagedata = json_decode($package_data,true);
                        foreach($packagedata as $pk=>$p){
                            $pnum = $p['num'] * $num;
                            Db::name('restaurant_product_guige')->where('aid',aid)->where('id',$p['ggid'])->update(['stock'=>Db::raw("stock-$pnum"),'sales'=>Db::raw("sales+$pnum"),'sales_daily'=>Db::raw("sales_daily+$pnum")]);
                            Db::name('restaurant_product')->where('aid',aid)->where('id',$p['proid'])->update(['stock'=>Db::raw("stock-$pnum"),'sales'=>Db::raw("sales+$pnum"),'sales_daily'=>Db::raw("sales_daily+$pnum")]);
                        }
                        Db::name('restaurant_shop_cart')->where('id',$cartdata['id'])->delete();
                    }
                }
			}
            //根据餐后付款设置，开启时下单后打印小票，关闭时付款后打印小票
//            $restaurant_shop_sysset = Db::name('restaurant_shop_sysset')->where('aid', aid)->where('bid', $data['bid'])->find();
//			if(getcustom('restaurant_shop_pindan')){
//			   if($table){
//                   if($table['pindan_status'] ==1){
//                       $restaurant_shop_sysset['pay_after'] = 1;
//                       $shop_sysset['pay_after'] = 1;
//                   } else{
//                       $restaurant_shop_sysset['pay_after'] = 0;
//                       $shop_sysset['pay_after'] = 0;
//                   }
//               }else{
//                   $shop_sysset['pay_after'] = 0;
//                   $restaurant_shop_sysset['pay_after'] = 0;
//               }
//            }
//		    $print_type = '';
//            if($restaurant_shop_sysset['pay_after'] == 1) {
//                $print_type = 0; //餐后付款只打印小票
//            }
//            \app\custom\Restaurant::print('restaurant_shop',$orderdata,[],$print_type);
            $store_name = Db::name('admin_set')->where('aid',aid)->value('name');
			//公众号通知 订单提交成功
			$tmplcontent = [];
			$tmplcontent['first'] = '有新点餐订单提交成功';
			$tmplcontent['remark'] = '点击进入查看~';
			$tmplcontent['keyword1'] = $store_name; //店铺
			$tmplcontent['keyword2'] = date('Y-m-d H:i:s',$orderdata['createtime']);//下单时间
			$tmplcontent['keyword3'] = $orderdata['title'];//菜品
			$tmplcontent['keyword4'] = $orderdata['totalprice'].'元';//金额
            $tempconNew = [];
            $tempconNew['character_string2'] = $orderdata['ordernum'];//订单号
            $tempconNew['thing8'] = $store_name;//门店名称
            $tempconNew['thing3'] = $orderdata['title'];//商品名称
            $tempconNew['amount7'] = $orderdata['totalprice'];//金额
            $tempconNew['time4'] = date('Y-m-d H:i:s',$orderdata['createtime']);//下单时间
			\app\common\Wechat::sendhttmpl(aid,$orderdata['bid'],'tmpl_orderconfirm',$tmplcontent,m_url('admin/restaurant/shoporder'),$orderdata['mdid'],$tempconNew);
			
			$tmplcontent = [];
			$tmplcontent['thing11'] = $orderdata['title'];
			$tmplcontent['character_string2'] = $orderdata['ordernum'];
			$tmplcontent['phrase10'] = '待付款';
			$tmplcontent['amount13'] = $orderdata['totalprice'].'元';
			$tmplcontent['thing27'] = $this->member['nickname'];
			\app\common\Wechat::sendhtwxtmpl(aid,$orderdata['bid'],'tmpl_orderconfirm',$tmplcontent,'admin/restaurant/shoporder',$orderdata['mdid']);
		}
   
        if(count($buydata) > 1){ //创建合并支付单
            $payparams = [];//payorder表额外参数
            if(getcustom('member_level_moneypay_price')){
                $payparams['putongprice'] = $alltotalputongprice && $alltotalputongprice>0?$alltotalputongprice:0;//所有商品普通价格总价
            }
			$payorderid = \app\model\Payorder::createorder(aid,0,mid,'restaurant_shop_hb',$orderid,$ordernum,$orderdata['title'],$alltotalprice,$alltotalscore,0,$payparams);
		}

		return $this->json(['status'=>1,'payorderid'=>$payorderid,'msg'=>'提交成功','pay_after' => $shop_sysset['pay_after']]);
	}

    //编辑加菜
    public function editOrder(){
        $post = input('post.');
        if($post['frompage'] != 'admin') {
            //非管理员点餐验证登录
            $this->checklogin();
        }
        if(empty($post['tableid'])) {
            return $this->json(['status'=>0,'msg'=>'请先扫描桌台二维码或选择桌台']);
        }

        //todo 一个桌子同时只能点一单
        $table = Db::name('restaurant_table')->where('aid',aid)->where('id', $post['tableid'])->find();

        if(getcustom('restaurant_book_order') && $post['orderid']){
            $table['orderid'] = $post['orderid'];
        }

        //桌子有订单号时,并且订单内有菜，为加菜
        if($table['orderid']) {
            $order = Db::name('restaurant_shop_order')->where('aid',aid)->where('id', $table['orderid'])->find();
            if($order && $order['status'] > 0 && $post['frompage'] != 'admin'){
                return $this->json(['status'=>0,'msg'=>'当前桌台存在未结束的订单，请联系服务员清台后重新下单']);
            }
            $order['goods_count'] = Db::name('restaurant_shop_order_goods')->where('aid',aid)->where('orderid', $order['id'])->count();
        }
        $shop_set = Db::name('restaurant_shop_sysset')->where('aid',aid)->where('bid',$order['bid'])->find();
        
        $mid = $order['mid'] ? $order['mid'] :$post['frompage']=='admin' ? 0: mid;
        
        if (getcustom('restaurant_shop_pindan')) {
            if($table['pindan_status'] ==1){
                //组合mids
                $mid = mid;
                $mids = [];
                if($order['mids']){
                    $mids = explode(',',$order['mids']);
                }
                if(!in_array($mid,$mids)){
                    $mids[] = $mid;
                    Db::name('restaurant_shop_order')->where('aid',aid)->where('id', $table['orderid'])->update(['mids' => implode(',',$mids)]);
                }
            }
        }
        $member = Db::name('member')->where('aid',aid)->where('id', $mid)->find();

        $ordertype = $order['goods_count'] ? 'edit_order' : 'create_order';//加菜，点菜

        $sysset = Db::name('admin_set')->where('aid',aid)->find();
        $levelid = Db::name('member')->where('aid',aid)->where('id', $mid)->value('levelid');
        $userlevel = Db::name('member_level')->where('aid',aid)->where('id',$levelid)->find();

        $buydata = $post['buydata'];
        $couponridArr = [];
        $userinfo = [];
        $userinfo['discount'] = $userlevel['discount'];
        $userinfo['score'] = $member['score'];
        $userinfo['score2money'] = $sysset['score2money'];
        $userinfo['scoredk_money'] = round($userinfo['score'] * $userinfo['score2money'],2);
        $userinfo['scoredkmaxpercent'] = $sysset['scoredkmaxpercent'];
        if(getcustom('sysset_scoredkmaxpercent_memberset')){
            //处理会员单独设置积分最大抵扣比例
            $userinfo['scoredkmaxpercent'] = $sysset['scoredkmaxpercent'] = \app\custom\ScoredkmaxpercentMemberset::dealmemberscoredk(aid,$this->member,$userinfo['scoredkmaxpercent']);
        }
        $userinfo['scoremaxtype'] = 0; //0最大百分比 1最大抵扣金额
        $userinfo['realname'] = $member['realname'];
        $userinfo['tel'] = $member['tel'];

        $ordernum = date('ymdHis').rand(100000,999999);
        
        $i = 0;
        $alltotalprice = 0;
        $alltotalscore = 0;
        Log::write([
            'file'=>__FILE__.__LINE__,
            '餐饮点餐订单编辑,orderid：'=>$table['orderid'],
            'post'=>json_encode(input('post.')),
            'mid'=>mid
        ]);
        foreach($buydata as $data){
            $scoredkmaxmoney = 0;
            $scoremaxtype = 0;

            $i++;
            $bid = $data['bid'];
            if($data['prodata']){
                $prodata = explode('-',$data['prodata']);
            }else{
                return $this->json(['status'=>0,'msg'=>'产品数据错误']);
            }
            if($bid!=0){
                $business = Db::name('business')->where('id',$bid)->field('id,aid,cid,name,logo,tel,address,sales,longitude,latitude,start_hours,end_hours')->find();
                if($business['start_hours'] != $business['end_hours']){
                    $start_time = strtotime(date('Y-m-d '.$business['start_hours']));
                    $end_time = strtotime(date('Y-m-d '.$business['end_hours']));
                    if(($start_time < $end_time && ($start_time > time() || $end_time < time())) || ($start_time >= $end_time && ($start_time > time() && $end_time < time()))){
                        return $this->json(['status'=>0,'msg'=>'商家不在营业时间']);
                    }
                }
            }
            $shop_set = Db::name('restaurant_shop_sysset')->where('aid',aid)->where('bid',$bid)->find();
            if($shop_set['status']==0){
                return $this->json(['status'=>0,'msg'=>'该商家未开启点餐']);
            }
            if($shop_set['start_hours'] != $shop_set['end_hours']){
                $start_time = strtotime(date('Y-m-d '.$shop_set['start_hours']));
                $end_time = strtotime(date('Y-m-d '.$shop_set['end_hours']));
                if(($start_time < $end_time && ($start_time > time() || $end_time < time())) || ($start_time >= $end_time && ($start_time > time() && $end_time < time()))){
                    return $this->json(['status'=>0,'msg'=>'该商家不在点餐时间']);
                }
            }

            $product_price = 0;
            $needzkproduct_price = 0;
            $givescore = 0; //奖励积分
            $totalweight = 0;//重量
            $totalnum = 0;
            $prolist = [];
            $proids = [];
            $cids = [];

            foreach($prodata as $key=>$pro){
                $sdata = explode(',',$pro);
                $sdata[2] = intval($sdata[2]);
                if($sdata[2] <= 0) return $this->json(['status'=>0,'msg'=>'购买数量有误']);
                $product = Db::name('restaurant_product')->where('aid',aid)->where('ischecked',1)->where('bid',$bid)->where('id',$sdata[0])->find();
                if(!$product) return $this->json(['status'=>0,'msg'=>'产品不存在或已下架']);

                if($product['status']==0){
                    return $this->json(['status'=>0,'msg'=>'菜品未上架']);
                }
                if($product['status']==2 && (strtotime($product['start_time']) > time() || strtotime($product['end_time']) < time())){
                    return $this->json(['status'=>0,'msg'=>'菜品未上架']);
                }
                if($product['status']==3){
                    $start_time = strtotime(date('Y-m-d '.$product['start_hours']));
                    $end_time = strtotime(date('Y-m-d '.$product['end_hours']));
                    if(($start_time < $end_time && ($start_time > time() || $end_time < time())) || ($start_time >= $end_time && ($start_time > time() && $end_time < time()))){
                        return $this->json(['status'=>0,'msg'=>'菜品未上架']);
                    }
                }

                if($key==0) $title = $product['name'];
                $deletegg = 1;
                if(getcustom('restaurant_product_package')){
                    $cartdata = Db::name('restaurant_shop_cart')->where('id',$sdata[3]) ->find();
                    //判断套餐是否参与
                    if($cartdata['package_data']){
                        $deletegg = 0;
                        $product_price+= $cartdata['package_price'] *$cartdata['num'];
                    }
                    if($product['product_type'] ==2 && $product['package_is_discount']==1){
                        $needzkproduct_price += $cartdata['package_price'] *$cartdata['num'];
                    }
                }
                $guige = Db::name('restaurant_product_guige')->where('aid',aid)->where('id',$sdata[1])->find();
                if(!$guige && $deletegg) return $this->json(['status'=>0,'msg'=>'产品规格不存在或已下架']);
                $is_check_stock = 1;
                if(getcustom('restaurant_weigh')){
                    if($product['product_type'] ==1){
                        //称重商品不校验库存
                        $is_check_stock = 0;
                    }
                }
                $is_check_daily_stock = 1;
                if(getcustom('restaurant_product_stock_daily')){
                    if($product['total_stock_daily'] > 0){
                        $is_check_daily_stock = 0;
                        if($sdata[2] > $product['total_stock_daily_real']){
                            return $this->json(['status'=>0,'msg'=>$product['name'].'的今日总库存不足']);
                        }
                    }
                }
                if($is_check_stock){
                    if($guige['stock'] < $sdata[2]){
                        return $this->json(['status'=>0,'msg'=>$product['name'].'库存不足']);
                    }
                    if($guige['stock_daily']-$guige['sales_daily']<$sdata[2] && $is_check_daily_stock){
                        return $this->json(['status'=>0,'msg'=>$product['name'].'今日库存不足']);
                    }
                }

                if($product['limit_per'] > 0 && $sdata[2] > $product['limit_per']){ //每单限购
                    return $this->json(['status'=>0,'msg'=>$product['name'].'每单限购'.$product['limit_per'].'份']);
                }
                if($product['limit_start'] > 0 && $sdata[2] < $product['limit_start']){ //起售份数
                    return $this->json(['status'=>0,'msg'=>$product['name'].'最低购买'.$product['limit_start'].'份']);
                }

                $guige = $this->formatguige($guige,$product['bid'],$product['lvprice']);
                $product_price += $guige['sell_price'] * $sdata[2];
                if($product['lvprice']==0){ //未开启会员价
                    $needzkproduct_price += $guige['sell_price'] * $sdata[2];
                }
                $cartid  =  intval($sdata[3]);//购物车
                if(getcustom('restaurant_product_jialiao')){
                    //如果商品设置打折
                    $jldata = Db::name('restaurant_shop_cart')->where('id',$cartid)->value('jldata');
                    $njlprice = 0;
                    $njltitle = '';
                    if($jldata){
                        $njldata = json_decode($jldata,true);
                        foreach($njldata as $key=>$val){
                            $njlprice += $val['num'] * $val['price'];
                            $njltitle .=$val['title'].'*'.$val['num'].'/';
                        }
                        $njltitle = rtrim($njltitle,'/');
                        $product_price +=  $njlprice;
                        if($product['jl_is_discount'] ==1){
                            $needzkproduct_price += $njlprice;
                        }
                    }

                }
                $totalweight += $guige['weight'] * $sdata[2];
                $totalnum += $sdata[2];

                 if($product['bid']>0){
                    //判断商家是否能自主修改积分设置
                    $business_selfscore = 0;
                    if(getcustom('business_selfscore') || getcustom('business_score_jiesuan')){
                        $business_selfscore = Db::name('business_sysset')->where('aid',aid)->value('business_selfscore');
                    }
                    $bcansetscore = false;//商家能否修改积分
                    if(getcustom('business_cansetscore')){
                        //能否修改积分
                        if($product['bid']){
                            $business_cansetscore = Db::name('business')->where('id',$product['bid'])->value('business_cansetscore');
                            $bcansetscore = $business_cansetscore && $business_cansetscore == 1?true:false;
                        }
                    }
                    if(!$business_selfscore && !$bcansetscore){
                        $product['scored_set'] = 0;
                    }
                }
                if($product['scored_set']==0){
					if($userinfo['scoredkmaxpercent'] == 0){
						$scoremaxtype = 1;
						$scoredkmaxmoney += 0;
					}else{
						if($userinfo['scoredkmaxpercent'] >= 0 && $userinfo['scoredkmaxpercent']<100){
							$scoredkmaxmoney += $userinfo['scoredkmaxpercent'] * 0.01 * $guige['sell_price'] * $sdata[2];
						}else{
							$scoredkmaxmoney += $guige['sell_price'] * $sdata[2];
						}
					}
                }elseif($product['scored_set']==1){
                    $scoremaxtype = 1;
                    $scoredkmaxmoney += $product['scored_val'] * 0.01 * $guige['sell_price'] * $sdata[2];
                }elseif($product['scored_set']==2){
                    $scoremaxtype = 1;
                    $scoredkmaxmoney += $product['scored_val'] * $sdata[2];
                }else{
                    $scoremaxtype = 1;
                    $scoredkmaxmoney += 0;
                }
                $remark = $data['remark'][$key];
                $prolist[] = ['product'=>$product,'guige'=>$guige,'num'=>$sdata[2],'cartid'=>$cartid,'remark' => $remark??''];

                $proids[] = $product['id'];
                $cids = array_merge($cids,explode(',',$product['cid']));
                $givescore += $guige['givescore'] * $sdata[2];
            }

//            dd($prolist);
            //会员折扣
            $leveldk_money = 0;
            if($userlevel && $userlevel['discount']>0 && $userlevel['discount']<10){
                $leveldk_money = $needzkproduct_price * (1 - $userlevel['discount'] * 0.1);
            }
            $totalprice = $product_price - $leveldk_money;

            //积分抵扣
            $scoredkscore = 0;
            $scoredk_money = 0;
            $orderdata = [];
            $end_totalprice = $totalprice + $order['totalprice'];
            if(getcustom('restaurant_table_minprice')){
                $service_money = 0;
                $service_totalprice =$end_totalprice -$order['service_money'];
                if($table){
                    if($table['minprice'] > 0 && $service_totalprice < $table['minprice']){
                        //计算服务费
                        if($table['service_fee_type'] ==0){
                            $service_money = $table['service_fee'];
                        }
                        if($table['service_fee_type'] ==1){
                            $service_money = $table['service_fee']/100 * $service_totalprice;
                        }
                    } 
                }
            
                $end_totalprice =  $end_totalprice - $order['service_money'] +  $service_money;
                $orderdata['service_money'] = dd_money_format($service_money);
            }
            $orderdata['totalprice'] = dd_money_format($end_totalprice);
            $orderdata['product_price'] = $product_price + $order['product_price'];
            $orderdata['leveldk_money'] = $leveldk_money + $order['leveldk_money'];  //会员折扣
            if($order['bid'] ==0){
                $orderdata['givescore'] = $givescore + $order['givescore'];
            }
            $orderdata['message'] = $data['message'] . ' '. $order['message'];
            //重新生成单号
            $orderdata['ordernum'] = $ordernum;
            $orderid = $order['id'];
            if(getcustom('restaurant_table_timing')){
                if($table['timing_fee_type'] > 0){
                    $orderdata['timing_can_pay'] = 0;
                }
            }
            $rsupdate = Db::name('restaurant_shop_order')->where('id', $table['orderid'])->update($orderdata);
            if($rsupdate ===false){
                return $this->json(['status'=>0,'msg'=>'系统繁忙，请重试']);
            }
            $orderdata = Db::name('restaurant_shop_order')->where('id', $table['orderid'])->find();
            $rsupdate = Db::name('restaurant_shop_order_goods')->where('orderid',$table['orderid'])->update(['ordernum'=>$orderdata['ordernum']]);
            if($rsupdate ===false){
                return $this->json(['status'=>0,'msg'=>'系统繁忙，请重试']);
            }

            $payorderid = \app\model\Payorder::createorder(aid,$orderdata['bid'],$orderdata['mid'],'restaurant_shop',$orderid,$orderdata['ordernum'],$orderdata['title'],$orderdata['totalprice'],$orderdata['scoredkscore']);

            $alltotalprice += $orderdata['totalprice'];
            $alltotalscore += $orderdata['scoredkscore'];

            $istc1 = 0; //设置了按单固定提成时 只将佣金计算到第一个菜品里
            $istc2 = 0;
            $istc3 = 0;
            if(getcustom('restaurant_shop_pindan')){
                if($table['pindan_status'] ==1){
                    $lasttimes = Db::name('restaurant_shop_order_goods')->where('aid',aid)->where('bid',$orderdata['bid'])->where('orderid',$orderid)->order('times desc')->value('times');
                    $lasttimes=$lasttimes + 1;
                }
            }
            foreach($prolist as $key=>$v){
                $product = $v['product'];
                $guige = $v['guige'];
                $num = $v['num'];
                if(getcustom('product_jialiao')){
                    $cardata = Db::name('restaurant_shop_cart')->where('aid',aid)->where('mid',mid)->where('ggid',$guige['id'])->where('proid',$product['id'])->find();
                    $input_jldata =   urldecode(input('jldata'));
                    if($input_jldata && input('btype') == 1){
                        $jlstring = explode('-',$input_jldata);
                        $cardata['jlprice'] =  $jlstring[0];
                        $cardata['jltitle'] =  $jlstring[1];
                    }
                }
                $ogdata = [];
                if(getcustom('restaurant_product_jialiao')){
                    $njlprice = 0;
                    $njltitle = '';
                    //如果商品设置打折
                    $cartid  =  $v['cartid'];//购物车
                    $jldata = Db::name('restaurant_shop_cart')->where('id',$cartid)->value('jldata');
                    if($jldata){
                        $njldata = json_decode($jldata,true);
                        foreach($njldata as $key=>$val){
                            $njlprice += $val['num'] * $val['price'];
                            $njltitle .=$val['title'].'*'.$val['num'].'/';
                        }
                        $njltitle = rtrim($njltitle,'/');
                       
                    }
                }  
              
                $ogdata['aid'] = aid;
                $ogdata['bid'] = $product['bid'];
                $ogdata['mid'] = $mid;
                $ogdata['orderid'] = $orderid;
                $ogdata['ordernum'] = $orderdata['ordernum'];
                $ogdata['proid'] = $product['id'];
                $ogdata['name'] = $product['name'];
                $ogdata['pic'] = $product['pic'];
                $ogdata['procode'] = $product['procode'];
                $ogdata['ggid'] = $guige['id'];
                $ogdata['ggname'] = $guige['name'];
                //$ogdata['cid'] = $product['cid'];
                $ogdata['num'] = $num;
                if(getcustom('restaurant_weigh')){
                    $ogdata['weigh'] = $num;
                    $ogdata['product_type'] = $product['product_type'];
                }
                $ogdata['remark'] = $v['remark'];
                $ogdata['cost_price'] = $guige['cost_price'];
                $sell_price =  $guige['sell_price'];
                if(getcustom('restaurant_product_package')){
                    $cartdata = Db::name('restaurant_shop_cart')->where('id',$v['cartid'])->find();
                    if($cartdata['package_data']){
                        $sell_price = $cartdata['package_price'];
                        $ogdata['package_data'] = $cartdata['package_data'];
                        $ogdata['is_package'] = 1;
                    }
                }
                $og_totalprice = $num * $sell_price;
                $ogdata['sell_price'] = $sell_price;
                $ogdata['totalprice'] = $og_totalprice;
                if(getcustom('restaurant_product_jialiao')){
                    $ogdata['totalprice'] = $num * $guige['sell_price'] +$njlprice*$num; 
                    $ogdata['njlprice'] = $njlprice;
                    $ogdata['njltitle'] = $njltitle;
                }
                $ogdata['real_totalprice'] = $og_totalprice; //实际菜品销售金额

                $ogdata['status'] = 0;
                $ogdata['createtime'] = time();
                if(getcustom('product_jialiao')){
                    $ogdata['jlprice'] = $cardata['jlprice']?$cardata['jlprice']:0;
                    $ogdata['jltitle'] = $cardata['jltitle']?$cardata['jltitle']:'';
                }
                
                    //计算菜品实际金额  菜品金额 - 会员折扣 - 积分抵扣 - 满减抵扣 - 优惠券抵扣
                    if($sysset['fxjiesuantype'] == 1 || $sysset['fxjiesuantype'] == 2){
                        $allproduct_price = $product_price;
                        $og_leveldk_money = 0;
                        $og_coupon_money = 0;
                        $og_scoredk_money = 0;
                        $og_manjian_money = 0;
                        if($allproduct_price > 0 && $og_totalprice > 0){
                            if($leveldk_money){
                                $og_leveldk_money = $og_totalprice / $allproduct_price * $leveldk_money;
                            }
                            if($coupon_money){
                                $og_coupon_money = $og_totalprice / $allproduct_price * $coupon_money;
                            }
                            if($scoredk_money){
                                $og_scoredk_money = $og_totalprice / $allproduct_price * $scoredk_money;
                            }
                            if($manjian_money){
                                $og_manjian_money = $og_totalprice / $allproduct_price * $manjian_money;
                            }
                        }
                        $og_totalprice = round($og_totalprice - $og_coupon_money - $og_scoredk_money - $og_manjian_money,2);
                        if($og_totalprice < 0) $og_totalprice = 0;
                    }
                    $ogdata['real_totalprice'] = $og_totalprice; //实际菜品销售金额

                    Log::write([
                        'file'=>__FILE__.__LINE__,
                        'real_totalprice：'=>$og_totalprice,
                        'mid'=>mid
                    ]);

                    //计算佣金的菜品金额
                    $commission_totalprice = $ogdata['totalprice'];
                    if($sysset['fxjiesuantype'] == 1){ //按成交价格
                        $commission_totalprice = $ogdata['real_totalprice'];
                    }
                    if($sysset['fxjiesuantype']==2){ //按利润提成
                        $commission_totalprice = $ogdata['real_totalprice'] - $guige['cost_price'] * $num;
                    }
                    if($commission_totalprice < 0) $commission_totalprice = 0;

                    $pid = $member['pid'];
                    $agleveldata = Db::name('member_level')->where('aid',aid)->where('id',$levelid)->find();
                    if($agleveldata['can_agent'] > 0 && $agleveldata['commission1own']==1){
                        $pid = $mid;
                    }
                    if($product['commissionset']!=-1){
                        if($pid){
                            $parent1 = Db::name('member')->where('aid',aid)->where('id',$pid)->find();
                            if($parent1){
                                $agleveldata1 = Db::name('member_level')->where('aid',aid)->where('id',$parent1['levelid'])->find();
                                if($agleveldata1['can_agent']!=0){
                                    $ogdata['parent1'] = $parent1['id'];
                                }
                            }
                        }
                        if($parent1['pid']){
                            $parent2 = Db::name('member')->where('aid',aid)->where('id',$parent1['pid'])->find();
                            if($parent2){
                                $agleveldata2 = Db::name('member_level')->where('aid',aid)->where('id',$parent2['levelid'])->find();
                                if($agleveldata2['can_agent']>1){
                                    $ogdata['parent2'] = $parent2['id'];
                                }
                            }
                        }
                        if($parent2['pid']){
                            $parent3 = Db::name('member')->where('aid',aid)->where('id',$parent2['pid'])->find();
                            if($parent3){
                                $agleveldata3 = Db::name('member_level')->where('aid',aid)->where('id',$parent3['levelid'])->find();
                                if($agleveldata3['can_agent']>2){
                                    $ogdata['parent3'] = $parent3['id'];
                                }
                            }
                        }
                        if($product['commissionset']==1){//按菜品设置的分销比例
                            $commissiondata = json_decode($product['commissiondata1'],true);
                            if($commissiondata){
                                if($agleveldata1) $ogdata['parent1commission'] = $commissiondata[$agleveldata1['id']]['commission1'] * $commission_totalprice * 0.01;
                                if($agleveldata2) $ogdata['parent2commission'] = $commissiondata[$agleveldata2['id']]['commission2'] * $commission_totalprice * 0.01;
                                if($agleveldata3) $ogdata['parent3commission'] = $commissiondata[$agleveldata3['id']]['commission3'] * $commission_totalprice * 0.01;
                            }
                        }elseif($product['commissionset']==2){//按固定金额
                            $commissiondata = json_decode($product['commissiondata2'],true);
                            if($commissiondata){
                                if($agleveldata1) $ogdata['parent1commission'] = $commissiondata[$agleveldata1['id']]['commission1'] * $num;
                                if($agleveldata2) $ogdata['parent2commission'] = $commissiondata[$agleveldata2['id']]['commission2'] * $num;
                                if($agleveldata3) $ogdata['parent3commission'] = $commissiondata[$agleveldata3['id']]['commission3'] * $num;
                            }
                        }elseif($product['commissionset']==3){//提成是积分
                            $commissiondata = json_decode($product['commissiondata3'],true);
                            if($commissiondata){
                                if($agleveldata1) $ogdata['parent1score'] = $commissiondata[$agleveldata1['id']]['commission1'] * $num;
                                if($agleveldata2) $ogdata['parent2score'] = $commissiondata[$agleveldata2['id']]['commission2'] * $num;
                                if($agleveldata3) $ogdata['parent3score'] = $commissiondata[$agleveldata3['id']]['commission3'] * $num;
                            }
                        }else{ //按会员等级设置的分销比例
                            if($agleveldata1){
                                if($agleveldata1['commissiontype']==1){ //固定金额按单
                                    if($istc1==0){
                                        $ogdata['parent1commission'] = $agleveldata1['commission1'];
                                        $istc1 = 1;
                                    }
                                }else{
                                    $ogdata['parent1commission'] = $agleveldata1['commission1'] * $commission_totalprice * 0.01;
                                }
                            }
                            if($agleveldata2){
                                if($agleveldata2['commissiontype']==1){
                                    if($istc2==0){
                                        $ogdata['parent2commission'] = $agleveldata2['commission2'];
                                        $istc2 = 1;
                                    }
                                }else{
                                    $ogdata['parent2commission'] = $agleveldata2['commission2'] * $commission_totalprice * 0.01;
                                }
                            }
                            if($agleveldata3){
                                if($agleveldata3['commissiontype']==1){
                                    if($istc3==0){
                                        $ogdata['parent3commission'] = $agleveldata3['commission3'];
                                        $istc3 = 1;
                                    }
                                }else{
                                    $ogdata['parent3commission'] = $agleveldata3['commission3'] * $commission_totalprice * 0.01;
                                }
                            }
                        }
                    }
                if(getcustom('restaurant_shop_pindan')){
                    if($table['pindan_status'] ==1){
                        $ogdata['times'] =$lasttimes;
                    }
                }
                $ogid = Db::name('restaurant_shop_order_goods')->insertGetId($ogdata);
                $ogids[] = $ogid;
                if($ogdata['parent1'] && ($ogdata['parent1commission'] > 0 || $ogdata['parent1score'] > 0)){
                    Db::name('member_commission_record')->insert(['aid'=>aid,'mid'=>$ogdata['parent1'],'frommid'=>$mid,'orderid'=>$orderid,'ogid'=>$ogid,'type'=>'restaurant_shop','commission'=>$ogdata['parent1commission'],'score'=>$ogdata['parent1score'],'remark'=>'下级购买菜品奖励','createtime'=>time()]);
                }
                if($ogdata['parent2'] && ($ogdata['parent2commission'] || $ogdata['parent2score'])){
                    Db::name('member_commission_record')->insert(['aid'=>aid,'mid'=>$ogdata['parent2'],'frommid'=>$mid,'orderid'=>$orderid,'ogid'=>$ogid,'type'=>'restaurant_shop','commission'=>$ogdata['parent2commission'],'score'=>$ogdata['parent2score'],'remark'=>'下二级购买菜品奖励','createtime'=>time()]);
                }
                if($ogdata['parent3'] && ($ogdata['parent3commission'] || $ogdata['parent3score'])){
                    Db::name('member_commission_record')->insert(['aid'=>aid,'mid'=>$ogdata['parent3'],'frommid'=>$mid,'orderid'=>$orderid,'ogid'=>$ogid,'type'=>'restaurant_shop','commission'=>$ogdata['parent3commission'],'score'=>$ogdata['parent3score'],'remark'=>'下三级购买菜品奖励','createtime'=>time()]);
                }
                //删除购物车
                if($guige['id'] && $product['id']){
                    $is_use_mid =1;
                    $cartwhere = [];
                    $cartwhere[] =['ggid','=',$guige['id']];
                    $cartwhere[] =['proid','=',$guige['product_id']];
                    if(getcustom('restaurant_shop_pindan')){
                        if($table['pindan_status'] ==1){
                            $is_use_mid = 0;
                            $cartwhere[] = ['tableid','=',$post['tableid']];
                        }
                    }
                    if($is_use_mid){
                        $cartwhere[] =['mid' ,'=', mid];
                    }
                    Db::name('restaurant_shop_cart')->where($cartwhere)->delete(); 
                }
                Db::name('restaurant_product_guige')->where('aid',aid)->where('id',$guige['id'])->update(['stock'=>Db::raw("stock-$num"),'sales'=>Db::raw("sales+$num"),'sales_daily'=>Db::raw("sales_daily+$num")]);
                Db::name('restaurant_product')->where('aid',aid)->where('id',$product['id'])->update(['stock'=>Db::raw("stock-$num"),'sales'=>Db::raw("sales+$num"),'sales_daily'=>Db::raw("sales_daily+$num")]);
                if(getcustom('restaurant_product_stock_daily')){
                    if ($product['total_stock_daily_real'] > 0) {
                        Db::name('restaurant_product')->where('aid', aid)->where('id', $product['id'])->update(['total_stock_daily_real' => Db::raw("total_stock_daily_real-$num")]);
                    }
                }
                if(getcustom('restaurant_product_package')){
                    if($cartdata['package_data']){
                        $packagedata = json_decode($cartdata['package_data'],true);
                        foreach($packagedata as $pk=>$p){
                            $pnum = $p['num'] * $num;
                            Db::name('restaurant_product_guige')->where('aid',aid)->where('id',$p['ggid'])->update(['stock'=>Db::raw("stock-$pnum"),'sales'=>Db::raw("sales+$pnum"),'sales_daily'=>Db::raw("sales_daily+$pnum")]);
                            Db::name('restaurant_product')->where('aid',aid)->where('id',$p['proid'])->update(['stock'=>Db::raw("stock-$pnum"),'sales'=>Db::raw("sales+$pnum"),'sales_daily'=>Db::raw("sales_daily+$pnum")]);
                        }
                        Db::name('restaurant_shop_cart')->where('id',$cartdata['id'])->delete();
                    }
                }
            }

            //根据餐后付款设置，开启时下单后打印小票，关闭时付款后打印小票
            $restaurant_shop_sysset = Db::name('restaurant_shop_sysset')->where('aid', aid)->where('bid', $data['bid'])->find();
            if(getcustom('restaurant_shop_pindan')){
                if($table){
                    if($table['pindan_status'] ==1){
                        $restaurant_shop_sysset['pay_after'] = 1;
                        $shop_sysset['pay_after'] = 1;
                    } else{
                        $restaurant_shop_sysset['pay_after'] = 0;
                        $shop_sysset['pay_after'] = 0;
                    }
                }else{
                    $shop_sysset['pay_after'] = 0;
                    $restaurant_shop_sysset['pay_after'] = 0;
                }
            }
            if($restaurant_shop_sysset['pay_after'] == 1) {
                //仅打印加菜
                $orderGoods = Db::name('restaurant_shop_order_goods')->alias('og')->where('orderid',$orderid)->where('og.id', 'in', $ogids)->leftJoin('restaurant_product p', 'p.id=og.proid')
                    ->fieldRaw('og.*,p.area_id')->select()->toArray();
                \app\custom\Restaurant::print('restaurant_shop',$orderdata, $orderGoods);
            }

        }
        if(count($buydata) > 1){ //创建合并支付单
            $payorderid = \app\model\Payorder::createorder(aid,0,$mid,'restaurant_shop_hb',$orderid,$ordernum,$orderdata['title'],$alltotalprice,$alltotalscore);
        }

        return $this->json(['status'=>1,'payorderid'=>$payorderid,'msg'=>'提交成功', 'pay_after' => $shop_set['pay_after']]);
    }

	public function orderlist(){
		$st = input('param.st');
		if(!input('?param.st') || $st === ''){
			$st = 'all';
		}
		$where = [];
		$where[] = ['aid','=',aid];
//		$where[] = ['mid','=',mid];
		$where[] = ['delete','=',0];
		if($st == 'all'){
			
		}elseif($st == '0'){
			$where[] = ['status','=',0];
		}elseif($st == '1'){
			$where[] = ['status','in','1,12'];
		}elseif($st == '2'){
			$where[] = ['status','=',2];
		}elseif($st == '3'){
			$where[] = ['status','=',3];
		}elseif($st == '10'){
			$where[] = ['refund_status','>',0];
		}
       
        $mid = mid;
        $where[] = Db::raw("find_in_set({$mid},`mids`) or mid = {$mid}");
      
//        if($is_member){
//            $where[] = ['mid','=',mid];
//        }
		$pernum = 10;
		$pagenum = input('post.pagenum');
		if(!$pagenum) $pagenum = 1;
		$datalist = Db::name('restaurant_shop_order')->where($where)->page($pagenum,$pernum)->order('id desc')->select()->toArray();
		if(!$datalist) $datalist = array();
		foreach($datalist as $key=>$v){
            $datalist[$key]['procount'] = 0+Db::name('restaurant_shop_order_goods')->where('orderid',$v['id'])->sum('num');
		    $prolist= Db::name('restaurant_shop_order_goods')->where('orderid',$v['id'])->select()->toArray();
            if(getcustom('restaurant_weigh')){
                foreach($prolist as $pk=>$pro){
                    $prolist[$pk]['num'] = floatval($pro['num']);
                }
            }
            if(getcustom('restaurant_product_jialiao')){
                foreach($prolist as $gk=>$gv){
                    $prolist[$gk]['sell_price'] = dd_money_format($gv['sell_price'] + $gv['njlprice']);
                    if($gv['njltitle']) {
                        $prolist[$gk]['ggname'] = $gv['ggname'] . '(' . $gv['njltitle'] . ')';
                    }
                }
            }
            foreach($prolist as $pgk=>$pro){
                if(getcustom('restaurant_product_package')){
                    if($pro['package_data']){
                        $package_data = json_decode($pro['package_data'],true);
                        $ggtext = [];
                        foreach($package_data as $pdk=>$pd){
                            $t = 'x'.$pd['num'].' '.$pd['proname'];
                            if($pd['ggname'] !='默认规格'){
                                $t .='('.$pd['ggname'].')';
                            }
                            $ggtext[] = $t;
                        }
                        $prolist[$pgk]['ggtext'] =$ggtext;
                    }
                }
            }
			$datalist[$key]['prolist'] = $prolist; 
			if(!$prolist) $datalist[$key]['prolist'] = [];
		
			if($v['bid']!=0){
				$datalist[$key]['binfo'] = Db::name('business')->where('aid',aid)->where('id',$v['bid'])->field('id,name,logo')->find();
			}else{
				$datalist[$key]['binfo'] = Db::name('admin_set')->where('aid',aid)->field('id,name,logo')->find();
			}
			$commentdp = Db::name('business_comment')->where('orderid',$v['id'])->where('aid',aid)->where('mid',mid)->find();
			if($commentdp){
				$datalist[$key]['iscommentdp'] = 1;
			}else{
				$datalist[$key]['iscommentdp'] = 0;
			}
			$is_topay = 1;
			if(getcustom('restaurant_table_timing')){             
			    $timing_fee_type = Db::name('restaurant_table')->where('aid',$v['aid'])->where('bid',$v['bid'])->where('id',$v['tableid'])->value('timing_fee_type');
			    if($timing_fee_type > 0 && $v['timing_can_pay'] ==0){
                    $is_topay = 0;
                }
            }
            $datalist[$key]['is_topay'] =$is_topay;
		}
		$rdata = [];
		$rdata['datalist'] = $datalist;
		$rdata['codtxt'] = Db::name('shop_sysset')->where('aid',aid)->value('codtxt');
		$rdata['st'] = $st;
		return $this->json($rdata);
	}
	public function orderdetail(){
		$detail = Db::name('restaurant_shop_order')->where('id',input('param.id/d'))->where('aid',aid)->find();
		if(empty($detail)) $this->json(['status'=>0,'msg'=>'订单不存在']);
		//可在6小时内查看非本人订单
        if(mid != $detail['mid'] && time() > ($detail['createtime'] + 3600*6)) {
            $this->json(['status'=>0,'msg'=>'订单不存在']);
        }

		$detail['createtime'] = $detail['createtime'] ? date('Y-m-d H:i:s',$detail['createtime']) : '';
		$detail['collect_time'] = $detail['collect_time'] ? date('Y-m-d H:i:s',$detail['collect_time']) : '';
		$detail['paytime'] = $detail['paytime'] ? date('Y-m-d H:i:s',$detail['paytime']) : '';
		$detail['refund_time'] = $detail['refund_time'] ? date('Y-m-d H:i:s',$detail['refund_time']) : '';
		$detail['send_time'] = $detail['send_time'] ? date('Y-m-d H:i:s',$detail['send_time']) : '';

		$storeinfo = [];
		if($detail['freight_type'] == 1){
			if($detail['bid'] == 0){
				$storeinfo = Db::name('mendian')->where('id',$detail['mdid'])->field('name,address,longitude,latitude')->find();
			}else{
				$storeinfo = Db::name('business')->where('id',$detail['bid'])->field('name,address,longitude,latitude')->find();
			}
		}
		
		if($detail['bid'] > 0){
			$detail['binfo'] = Db::name('business')->where('aid',aid)->where('id',$detail['bid'])->field('id,name,logo')->find();
		}else{
			$detail['binfo'] = Db::name('admin_set')->where('aid',aid)->field('id,name,logo')->find();
		}
		$iscommentdp = 0;
		$commentdp = Db::name('business_comment')->where('orderid',$detail['id'])->where('aid',aid)->where('mid',mid)->find();
		if($commentdp) $iscommentdp = 1;

		$prolist = Db::name('restaurant_shop_order_goods')->where('orderid',$detail['id'])->order('id desc')->select()->toArray();
        if(getcustom('restaurant_shop_pindan')){
            foreach($prolist as $key=>$val){
                if($val['mid'] == mid){
                    $prolist[$key]['is_show_comment'] =  1;
                }else{
                    $prolist[$key]['is_show_comment'] =  0;
                }

            }
        }
        if(getcustom('restaurant_product_jialiao')){
            foreach($prolist as $gk=>$gv){
                $prolist[$gk]['sell_price'] = dd_money_format($gv['sell_price'] + $gv['njlprice']);
                if($gv['njltitle']){
                    $prolist[$gk]['ggname'] = $gv['ggname'] .'('. $gv['njltitle'].')';
                }
            }
        }
        if(getcustom('restaurant_weigh')){
            foreach($prolist as $wgk=>$wgv){    
                $prolist[$wgk]['num'] = floatval($wgv['num']);
            }
        }
        if(getcustom('restaurant_product_package')){
            foreach($prolist as $key=>$val){
                if($val['package_data']){
                    $package_data = json_decode($val['package_data'],true);
                    $ggtext = [];
                    foreach($package_data as $pdk=>$pd){
                        $t = 'x'.$pd['num'].' '.$pd['proname'];
                        if($pd['ggname'] !='默认规格'){
                            $t .='('.$pd['ggname'].')';
                        }
                        $ggtext[] = $t;
                    }
                    $prolist[$key]['ggtext'] =$ggtext;
                }
            }
        }
		$shopset = Db::name('shop_sysset')->where('aid',aid)->field('comment,autoclose')->find();
        
        
        $shop_set = Db::name('restaurant_shop_sysset')->where('aid',aid)->where('bid',$detail['bid'])->find();
        $shopset['is_times_prolist'] = 0;//是否是带下单次数的产品列表
        if($detail['eattype'] ==1){
            $timesprolist = [];
            $tprolist = [];
            foreach($prolist as $key=>$val){
                $tprolist[$val['times']]['prolist'][] = $val;
                $tprolist[$val['times']]['createtime'] = date('H:i',$val['createtime']);
                $tprolist[$val['times']]['times'] = $val['times']?$val['times']:1;
            }
            foreach($tprolist as $k=>$v){
                $timesprolist[] = $v;
            }
            $prolist = $timesprolist;
        }
//        if(getcustom('restaurant_shop_pindan')){
//            $pdtable = Db::name('restaurant_table')->where('id',$detail['tableid'])->find();
//            if($pdtable){
//                if($pdtable['pindan_status'] ==1){
//                    $shop_set['pay_after'] = 1;
//                } else{
//                    $shop_set['pay_after'] = 0;
//                }
//            }else{
//                $shop_set['pay_after'] = 0;
//            }
//            if($pdtable['pindan_status'] ==1){
//                $timesprolist = [];
//                $tprolist = [];
//                foreach($prolist as $key=>$val){
//                    $tprolist[$val['times']]['prolist'][] = $val;
//                    $tprolist[$val['times']]['createtime'] = date('H:i',$val['createtime']);
//                    $tprolist[$val['times']]['times'] = $val['times']?$val['times']:1;
//                }
//                foreach($tprolist as $k=>$v){
//                    $timesprolist[] = $v;
//                }
//                $prolist = $timesprolist;
//                $shopset['is_times_prolist'] = 1;
//            } 
//            
//        }
        
        $shopset = array_merge($shopset,$shop_set);
		
		if($detail['status']==0 && $shopset['autoclose'] > 0){
			$lefttime = strtotime($detail['createtime']) + $shopset['autoclose']*60 - time();
			if($lefttime < 0) $lefttime = 0;
		}else{
			$lefttime = 0;
		}
		
		if($detail['field1']){
			$detail['field1data'] = explode('^_^',$detail['field1']);
		}
		if($detail['field2']){
			$detail['field2data'] = explode('^_^',$detail['field2']);
		}
		if($detail['field3']){
			$detail['field3data'] = explode('^_^',$detail['field3']);
		}
		if($detail['field4']){
			$detail['field4data'] = explode('^_^',$detail['field4']);
		}
		if($detail['field5']){
			$detail['field5data'] = explode('^_^',$detail['field5']);
		}

        $detail['tableName'] = Db::name('restaurant_table')->where('id',$detail['tableid'])->value('name');
		if(getcustom('product_jialiao')){
            $detail['product_price'] = bcadd($detail['product_price'],$detail['jlprice'],2);
        }
        //开启餐后付款用户不可关闭订单（可能厨房已经做好或者已经吃了）

        $detail['tabletext'] = '桌号';
        if(getcustom('restaurant_table_name')){
        	$tabletext  = Db::name('restaurant_shop_sysset')->where('aid',aid)->where('bid',$detail['bid'])->value('table_text');
        	$detail['tabletext'] = !empty($tabletext)?$tabletext:'桌号';
        }
        $is_topay = 1;
        if(getcustom('restaurant_table_timing')){
            $timing_fee_type = Db::name('restaurant_table')->where('aid',$detail['aid'])->where('bid',$detail['bid'])->where('id',$detail['tableid'])->value('timing_fee_type');
            if($timing_fee_type > 0 && $detail['timing_can_pay'] ==0){
                $is_topay = 0;
            }
        }
        $detail['is_topay'] = $is_topay;
        $detail['show_printdaynum'] = 0;
        if(getcustom('sys_print_set')){
            $detail['show_printdaynum'] = 1;
        }
        if(getcustom('restaurant_is_apply_refund')){
            $is_apply_refund = Db::name('restaurant_admin_set')->where('aid',aid)->value('is_apply_refund');
            $shopset['is_apply_refund']=  $is_apply_refund;
            if($detail['bid'] > 0){
                $tel= Db::name('business')->where('aid',aid)->where('id',$detail['bid'])->value('tel');
            }else{
                $tel = Db::name('admin_set')->where('aid',aid)->value('tel');
            }
            $shopset['tel']=  $tel;
        }
		$rdata = [];
		$rdata['detail'] = $detail;
		$rdata['iscommentdp'] = $iscommentdp;
		$rdata['prolist'] = $prolist;
		$rdata['timesprolist'] = $timesprolist;
		$rdata['shopset'] = $shopset;
		$rdata['storeinfo'] = $storeinfo;
		$rdata['lefttime'] = $lefttime;
		return $this->json($rdata);
	}
	//取消订单
	function quxiao(){
//		$post = input('post.');
//		$orderid = intval($post['orderid']);
//		$order = Db::name('restaurant_shop_order')->where('id',$orderid)->where('aid',aid)->where('mid',mid)->find();
//		if(!$order || $order['status']!=1){
//			return $this->json(['status'=>0,'msg'=>'取消失败,订单状态错误']);
//		}
//		$refund_money = $order['totalprice'];
//		$reason = '用户取消订单';
//		if($refund_money > 0) {
//            $rs = \app\common\Order::refund($order,$refund_money,$reason);
//            if($rs['status']==0){
//                return json(['status'=>0,'msg'=>$rs['msg']]);
//            }
//        }
//
//		Db::name('restaurant_shop_order')->where('id',$orderid)->where('aid',aid)->where('bid',bid)->update(['status'=>4,'refund_status'=>2,'refund_money'=>$refund_money,'refund_reason'=>$reason]);
//		Db::name('restaurant_shop_order_goods')->where('orderid',$orderid)->where('aid',aid)->where('bid',bid)->update(['status'=>4]);
//
//		//积分抵扣的返还
//		if($order['scoredkscore'] > 0){
//			\app\common\Member::addscore(aid,$order['mid'],$order['scoredkscore'],'订单退款返还');
//		}
//		//优惠券抵扣的返还
//		if($order['coupon_rid'] > 0){
//			Db::name('coupon_record')->where('aid',aid)->where(['mid'=>$order['mid'],'id'=>$order['coupon_rid']])->update(['status'=>0,'usetime'=>'']);
//		}
//
//		//退款成功通知
//		$tmplcontent = [];
//		$tmplcontent['first'] = '您的订单已经完成退款，¥'.$refund_money.'已经退回您的付款账户，请留意查收。';
//		$tmplcontent['remark'] = $reason.'，请点击查看详情~';
//		$tmplcontent['orderProductPrice'] = $refund_money;
//		$tmplcontent['orderProductName'] = $order['title'];
//		$tmplcontent['orderName'] = $order['ordernum'];
//		\app\common\Wechat::sendtmpl(aid,$order['mid'],'tmpl_tuisuccess',$tmplcontent,m_url('restaurant/shop/orderlist'));
//		//订阅消息
//		$tmplcontent = [];
//		$tmplcontent['amount6'] = $refund_money;
//		$tmplcontent['thing3'] = $order['title'];
//		$tmplcontent['character_string2'] = $order['ordernum'];
//
//		$tmplcontentnew = [];
//		$tmplcontentnew['amount3'] = $refund_money;
//		$tmplcontentnew['thing6'] = $order['title'];
//		$tmplcontentnew['character_string4'] = $order['ordernum'];
//		\app\common\Wechat::sendwxtmpl(aid,$order['mid'],'tmpl_tuisuccess',$tmplcontentnew,'restaurant/shop/orderlist',$tmplcontent);
//
//		//短信通知
//		$member = Db::name('member')->where('id',$order['mid'])->find();
//		if($member['tel']){
//			$tel = $member['tel'];
//		}else{
//			$tel = $order['tel'];
//		}
//		$rs = \app\common\Sms::send(aid,$tel,'tmpl_tuisuccess',['ordernum'=>$order['ordernum'],'money'=>$refund_money]);
//
//		return json(['status'=>1,'msg'=>'已退款成功']);
	}
	function closeOrder(){
		$post = input('post.');
		$orderid = intval($post['orderid']);
		$order = Db::name('restaurant_shop_order')->where('id',$orderid)->where('aid',aid)->where('mid',mid)->find();
		if(!$order || $order['status']!=0){
			return $this->json(['status'=>0,'msg'=>'关闭失败,订单状态错误']);
		}
		//加库存
		$oglist = Db::name('restaurant_shop_order_goods')->where('aid',aid)->where('orderid',$orderid)->select()->toArray();
		foreach($oglist as $og){
			Db::name('restaurant_product_guige')->where('aid',aid)->where('id',$og['ggid'])->update(['stock'=>Db::raw("stock+".$og['num']),'sales'=>Db::raw("sales-".$og['num'])]);
			Db::name('restaurant_product')->where('aid',aid)->where('id',$og['proid'])->update(['stock'=>Db::raw("stock+".$og['num']),'sales'=>Db::raw("sales-".$og['num'])]);
			if($og['seckill_starttime']){
				Db::name('seckill_prodata')->where('aid',aid)->where('proid',$og['proid'])->where('ggid',$og['ggid'])->where('starttime',$og['seckill_starttime'])->dec('sales',$og['num'])->update();
			}
		}
		//优惠券抵扣的返还
		if($order['coupon_rid'] > 0){
            \app\common\Coupon::refundCoupon2($order['aid'],$order['mid'],$order['coupon_rid'],$order);
		}

		$rs = Db::name('restaurant_shop_order')->where('id',$orderid)->where('aid',aid)->where('mid',mid)->update(['status'=>4]);
		Db::name('restaurant_shop_order_goods')->where('orderid',$orderid)->where('aid',aid)->where('mid',mid)->update(['status'=>4]);
		//清除桌台
        if($order['tableid'] > 0){
            $where  = [];
            $where[] = ['id','=',$order['tableid']];
            $where[] = ['aid','=',$order['aid']];
            if(!getcustom('extend_qrcode_variable_fenzhang')){
                $where[] = ['bid','=',$order['bid']];
            }
            Db::name('restaurant_table')->where($where)->update(['status' => 0, 'orderid' => 0]);
        }
		return $this->json(['status'=>1,'msg'=>'操作成功']);
	}
	function delOrder(){
		$post = input('post.');
		$orderid = intval($post['orderid']);
		$order = Db::name('restaurant_shop_order')->where('id',$orderid)->where('aid',aid)->where('mid',mid)->find();
		if(!$order || ($order['status']!=4 && $order['status']!=3)){
			return $this->json(['status'=>0,'msg'=>'删除失败,订单状态错误']);
		}
//		if($order['status']==3){
			$rs = Db::name('restaurant_shop_order')->where('id',$orderid)->where('aid',aid)->where('mid',mid)->update(['delete'=>1]);
//		}else{
//			$rs = Db::name('restaurant_shop_order')->where('id',$orderid)->where('aid',aid)->where('mid',mid)->delete();
//			$rs = Db::name('restaurant_shop_order_goods')->where('orderid',$orderid)->where('aid',aid)->where('mid',mid)->delete();
//		}
		return $this->json(['status'=>1,'msg'=>'删除成功']);
	}
	function orderCollect(){ //确认收货
		$post = input('post.');
		$orderid = intval($post['orderid']);
		$order = Db::name('restaurant_shop_order')->where('aid',aid)->where('mid',mid)->where('id',$orderid)->find();
		if(!$order || ($order['status']!=2) || $order['paytypeid']==4){
			return $this->json(['status'=>0,'msg'=>'订单状态不符合收货要求']);
		}
        $rs = \app\custom\Restaurant::shop_orderconfirm($orderid);
		if($rs['status'] == 0) return $this->json($rs);

//		Db::name('restaurant_shop_order')->where('aid',aid)->where('mid',mid)->where('id',$orderid)->update(['status'=>3,'collect_time'=>time()]);
//		Db::name('restaurant_shop_order_goods')->where('aid',aid)->where('orderid',$orderid)->update(['status'=>3,'endtime'=>time()]);
		\app\common\Member::uplv(aid,mid);
		$return = ['status'=>1,'msg'=>'确认收货成功','url'=>true];

		$tmplcontent = [];
		$tmplcontent['first'] = '有订单客户已确认收货';
		$tmplcontent['remark'] = '点击进入查看~';
		$tmplcontent['keyword1'] = $this->member['nickname'];
		$tmplcontent['keyword2'] = $order['ordernum'];
		$tmplcontent['keyword3'] = $order['totalprice'].'元';
		$tmplcontent['keyword4'] = date('Y-m-d H:i',$order['paytime']);
        $tmplcontentNew = [];
        $tmplcontentNew['thing3'] = $this->member['nickname'];//收货人
        $tmplcontentNew['character_string7'] = $order['ordernum'];//订单号
        $tmplcontentNew['time8'] = date('Y-m-d H:i');//送达时间
		\app\common\Wechat::sendhttmpl(aid,$order['bid'],'tmpl_ordershouhuo',$tmplcontent,m_url('admin/order/shoporder'),$order['mdid'],$tmplcontentNew);

		$tmplcontent = [];
		$tmplcontent['thing2'] = $order['title'];
		$tmplcontent['character_string6'] = $order['ordernum'];
		$tmplcontent['thing3'] = $this->member['nickname'];
		$tmplcontent['date5'] = date('Y-m-d H:i');
		\app\common\Wechat::sendhtwxtmpl(aid,$order['bid'],'tmpl_ordershouhuo',$tmplcontent,'admin/order/shoporder',$order['mdid']);

		return $this->json($return);
	}
	public function refundinit(){
		//订阅消息
		$wx_tmplset = Db::name('wx_tmplset')->where('aid',aid)->find();
		$tmplids = [];
		if($wx_tmplset['tmpl_tuisuccess_new']){
			$tmplids[] = $wx_tmplset['tmpl_tuisuccess_new'];
		}elseif($wx_tmplset['tmpl_tuisuccess']){
			$tmplids[] = $wx_tmplset['tmpl_tuisuccess'];
		}
		if($wx_tmplset['tmpl_tuierror_new']){
			$tmplids[] = $wx_tmplset['tmpl_tuierror_new'];
		}elseif($wx_tmplset['tmpl_tuierror']){
			$tmplids[] = $wx_tmplset['tmpl_tuierror'];
		}
		$rdata = [];
		$rdata['tmplids'] = $tmplids;
		return $this->json($rdata);
	}
	function refund(){//申请退款
		if(request()->isPost()){
			$post = input('post.');
			$orderid = intval($post['orderid']);
			$money = floatval($post['money']);
			$order = Db::name('restaurant_shop_order')->where('aid',aid)->where('mid',mid)->where('id',$orderid)->find();
			if(!$order || ($order['status']!=1 && $order['status'] != 2) || $order['refund_status'] == 2){
				return $this->json(['status'=>0,'msg'=>'订单状态不符合退款要求']);
			}
			if($money < 0 || $money > $order['totalprice']){
				return $this->json(['status'=>0,'msg'=>'退款金额有误']);
			}
			Db::name('restaurant_shop_order')->where('aid',aid)->where('mid',mid)->where('id',$orderid)->update(['refund_time'=>time(),'refund_status'=>1,'refund_reason'=>$post['reason'],'refund_money'=>$money]);

			$tmplcontent = [];
			$tmplcontent['first'] = '有订单客户申请退款';
			$tmplcontent['remark'] = '点击进入查看~';
			$tmplcontent['keyword1'] = $order['ordernum'];
			$tmplcontent['keyword2'] = $money.'元';
			$tmplcontent['keyword3'] = $post['reason'];
            $tmplcontentNew = [];
            $tmplcontentNew['number2'] = $order['ordernum'];//订单号
            $tmplcontentNew['amount4'] = $money;//退款金额
			\app\common\Wechat::sendhttmpl(aid,$order['bid'],'tmpl_ordertui',$tmplcontent,m_url('admin/restaurant/shoporder'),$order['mdid'],$tmplcontentNew);
			
			$tmplcontent = [];
			$tmplcontent['thing1'] = $order['title'];
			$tmplcontent['character_string4'] = $order['ordernum'];
			$tmplcontent['amount2'] = $order['totalprice'];
			$tmplcontent['amount9'] = $money.'元';
			$tmplcontent['thing10'] = $post['reason'];
			\app\common\Wechat::sendhtwxtmpl(aid,$order['bid'],'tmpl_ordertui',$tmplcontent,'admin/restaurant/shoporder',$order['mdid']);

			return $this->json(['status'=>1,'msg'=>'提交成功,请等待商家审核']);
		}
		$orderid = input('param.orderid/d');
		$price = input('param.price/f');
		$order = Db::name('restaurant_shop_order')->where('aid',aid)->where('mid',mid)->where('id',$orderid)->find();
		$price = $order['totalprice'];
		$this->assign('orderid',$orderid);
		$this->assign('price',$price);
		return $this->fetch();
	}
	//评价菜品
	public function comment(){
		$ogid = input('param.ogid/d');
		$og = Db::name('restaurant_shop_order_goods')->where('id',$ogid)->where('mid',mid)->find();
		if(!$og){
			return $this->json(['status'=>0,'msg'=>'未查找到相关记录']);
		}
		$comment = Db::name('restaurant_shop_comment')->where('ogid',$ogid)->where('aid',aid)->where('mid',mid)->find();
		if(request()->isPost()){
			$shopset = Db::name('shop_sysset')->where('aid',aid)->find();
			if($shopset['comment']==0) return $this->json(['status'=>0,'msg'=>'评价功能未开启']);
			if($comment){
				return $this->json(['status'=>0,'msg'=>'您已经评价过了']);
			}
			$order_good = Db::name('restaurant_shop_order_goods')->where('aid',aid)->where('mid',mid)->where('id',$ogid)->find();
			$order = Db::name('restaurant_shop_order')->where('id',$order_good['orderid'])->find();
			$content = input('post.content');
			$content_pic = input('post.content_pic');
			$score = input('post.score/d');
			if($score < 1){
				return $this->json(['status'=>0,'msg'=>'请打分']);
			}
			$data['aid'] = aid;
			$data['mid'] = mid;
			$data['ogid'] = $order_good['id'];
			$data['proid'] =$order_good['proid'];
			$data['proname'] = $order_good['name'];
			$data['propic'] = $order_good['pic'];
			$data['orderid']= $order['id'];
			$data['ordernum']= $order['ordernum'];
			$data['score'] = $score;
			$data['content'] = $content;
			$data['openid']= $this->member['openid'];
			$data['nickname']= $this->member['nickname'];
			$data['headimg'] = $this->member['headimg'];
			$data['createtime'] = time();
			$data['content_pic'] = $content_pic;
			$data['ggid'] = $order_good['ggid'];
			$data['ggname'] = $order_good['ggname'];
			$data['status'] = ($shopset['comment_check']==1 ? 0 : 1);
			Db::name('restaurant_shop_comment')->insert($data);
			Db::name('restaurant_shop_order_goods')->where('aid',aid)->where('mid',mid)->where('id',$ogid)->update(['iscomment'=>1]);
			//Db::name('restaurant_shop_order')->where('id',$order['id'])->update(['iscomment'=>1]);
			
			//如果不需要审核 增加产品评论数及评分
			if($shopset['comment_check']==0){
				$countnum = Db::name('restaurant_shop_comment')->where('proid',$order_good['proid'])->where('status',1)->count();
				$score = Db::name('restaurant_shop_comment')->where('proid',$order_good['proid'])->where('status',1)->avg('score'); //平均评分
				$haonum = Db::name('restaurant_shop_comment')->where('proid',$order_good['proid'])->where('status',1)->where('score','>',3)->count(); //好评数
				if($countnum > 0){
					$haopercent = $haonum/$countnum*100;
				}else{
					$haopercent = 100;
				}
				Db::name('restaurant_product')->where('id',$order_good['proid'])->update(['comment_num'=>$countnum,'comment_score'=>$score,'comment_haopercent'=>$haopercent]);
			}
			return $this->json(['status'=>1,'msg'=>'评价成功']);
		}
		$rdata = [];
		$rdata['og'] = $og;
		$rdata['comment'] = $comment;
		return $this->json($rdata);
	}
	//评价店铺
	public function commentdp(){
		$orderid = input('param.orderid/d');
		$order = Db::name('restaurant_shop_order')->where('id',$orderid)->where('mid',mid)->find();
		if(!$order){
			return $this->json(['status'=>0,'msg'=>'未查找到相关记录']);
		}
		$comment = Db::name('business_comment')->where('orderid',$orderid)->where('aid',aid)->where('mid',mid)->find();
		if(request()->isPost()){
			if($comment){
				return $this->json(['status'=>0,'msg'=>'您已经评价过了']);
			}
			$content = input('post.content');
			$content_pic = input('post.content_pic');
			$score = input('post.score/d');
			if($score < 1){
				return $this->json(['status'=>0,'msg'=>'请打分']);
			}
			$data['aid'] = aid;
			$data['mid'] = mid;
			$data['bid'] = $order['bid'];
			$data['bname'] = Db::name('business')->where('id',$order['bid'])->value('name');
			$data['orderid']= $order['id'];
			$data['ordernum']= $order['ordernum'];
			$data['score'] = $score;
			$data['content'] = $content;
			$data['content_pic'] = $content_pic;
			$data['openid']= $this->member['openid'];
			$data['nickname']= $this->member['nickname'];
			$data['headimg'] = $this->member['headimg'];
			$data['createtime'] = time();
			$data['status'] = 1;
			Db::name('business_comment')->insert($data);
			
			//如果不需要审核 增加店铺评论数及评分
			$countnum = Db::name('business_comment')->where('bid',$order['bid'])->where('status',1)->count();
			$score = Db::name('business_comment')->where('bid',$order['bid'])->where('status',1)->avg('score');
			Db::name('business')->where('id',$order['bid'])->update(['comment_num'=>$countnum,'comment_score'=>$score]);
			return $this->json(['status'=>1,'msg'=>'评价成功']);
		}
		$rdata = [];
		$rdata['order'] = $order;
		$rdata['comment'] = $comment;
		return $this->json($rdata);
	}
	//评价配送员
	public function commentps(){
		$id = input('param.id/d');
		$psorder = Db::name('peisong_order')->where('id',$id)->where('mid',mid)->find();
		if(!$psorder) return $this->json(['status'=>0,'msg'=>'未找到相关记录']);
		$comment = Db::name('peisong_order_comment')->where('orderid',$id)->where('aid',aid)->where('mid',mid)->find();
		if(request()->isPost()){
			if($comment){
				return $this->json(['status'=>0,'msg'=>'您已经评价过了']);
			}
			$content = input('post.content');
			$content_pic = input('post.content_pic');
			$score = input('post.score/d');
			if($score < 1){
				return $this->json(['status'=>0,'msg'=>'请打分']);
			}
			$data['aid'] = aid;
			$data['mid'] = mid;
			$data['bid'] = $psorder['bid'];
			$data['psid'] = $psorder['psid'];
			$data['orderid']= $psorder['id'];
			$data['ordernum']= $psorder['ordernum'];
			$data['score'] = $score;
			$data['content'] = $content;
			$data['content_pic'] = $content_pic;
			$data['nickname']= $this->member['nickname'];
			$data['headimg'] = $this->member['headimg'];
			$data['createtime'] = time();
			$data['status'] = 1;
			Db::name('peisong_order_comment')->insert($data);
			
			//如果不需要审核 增加配送员评论数及评分
			$countnum = Db::name('peisong_order_comment')->where('psid',$psorder['psid'])->where('status',1)->count();
			$score = Db::name('peisong_order_comment')->where('psid',$psorder['psid'])->where('status',1)->avg('score'); //平均评分
			$haonum = Db::name('peisong_order_comment')->where('psid',$psorder['psid'])->where('status',1)->where('score','>',3)->count(); //好评数
			if($countnum > 0){
				$haopercent = $haonum/$countnum*100;
			}else{
				$haopercent = 100;
			}
			Db::name('peisong_user')->where('id',$psorder['psid'])->update(['comment_num'=>$countnum,'comment_score'=>$score,'comment_haopercent'=>$haopercent]);

			return $this->json(['status'=>1,'msg'=>'评价成功']);
		}
		$rdata = [];
		$rdata['psorder'] = $psorder;
		$rdata['comment'] = $comment;
		return $this->json($rdata);
	}
	//套餐详情
	public function getPackageData(){
        if(getcustom('restaurant_product_package')){
            $id = input('param.id',0);
            $where = [];
            $where[] = ['aid','=',aid];
            $where[] = ['id','=',$id];
            $info = Db::name('restaurant_product')->where($where)->find();
            if(!$info){
                return $this->json(['status'=>0,'msg'=>'菜品不存在']);
            }
            if(!$info['packagedata']){
                return $this->json(['status'=>0,'msg'=>'套餐不存在']);
            }
            $packagedata = json_decode($info['packagedata'],true);
            foreach($packagedata as $key =>$val){
                $prolist = $val['prolist'];
                if($prolist){
                    foreach($prolist as $pk=>$pro){
                        $product =  Db::name('restaurant_product')->where('id',$pro['proid'])->field('pic,guigedata')->find();
                        $propic =$product['pic'];
                        if($pro['ggid'] > 0){
                            $ggpic = Db::name('restaurant_product_guige')->where('id',$pro['ggid'])->value('pic');
                        } else{
                            $ggfield = 'id as ggid,name as ggname,sell_price,pic,ks';
                            if(getcustom('restaurant_product_guige_hide')){
                                $ggfield .=',show_status';
                            }
                            $package_gglist = Db::name('restaurant_product_guige')->where('aid',aid)->where('product_id',$pro['proid'])->field($ggfield)->select()->toArray();
                            $ggpic = $package_gglist[0]['pic'];
                            $prolist[$pk]['pic'] =$ggpic?$ggpic:$propic;
                            $guigeks = [];
                            $not_selected = [];//不选中
                            foreach ($package_gglist as  $gg){
                                $guigeks[$gg['ks']] = $gg;
                                if(getcustom('restaurant_product_guige_hide')){
                                    if($gg['show_status'] ==1){
                                        $not_selected[] = $gg['ks'];
                                    }
                                }
                            }
                            $prolist[$pk]['guigedata'] = json_decode($product['guigedata'],true);
                            $prolist[$pk]['guigelist'] = $guigeks ?? [];
                           $prolist[$pk]['not_selected'] = $not_selected ?? [];
                        }

                        $prolist[$pk]['pic'] =$ggpic?$ggpic:$propic; 
                    }
                }
                $packagedata[$key]['prolist'] =  $prolist;
            }
            return  $this->json(['status' => 1,'data' => $packagedata,'product' => $info]); 
        }
    }
    //获取桌台的 订单信息和 购物车信息
    public function getTableOrder(){
        $tableid = input('param.tableId');
        $bid = input('param.bid/d', 0);
        $renshu = input('param.renshu');
        $prodata = explode('-',input('param.prodata'));
        $table = Db::name('restaurant_table')->where('aid',aid)->where('bid',$bid)->where('id',$tableid)->find();
        if(!$table)return $this->json(['status'=>0,'msg'=>'桌台异常']);
        $order = Db::name('restaurant_shop_order')->where('id',$table['orderid'])->find();
        if($order && $order['status'] ==1)return $this->json(['status'=>0,'msg'=>'订单已结算，桌台清台中']);
        if($order && $order['status'] ==4)return $this->json(['status'=>0,'msg'=>'订单已关闭']);
        $allbuydata = [];
        $prodataArr = [];
        $bid = 0;
        if(getcustom('restaurant_table_default_product')){  
            if(!$table['orderid']){
                if($table['default_product_bxdata']){
                    $bxdata = json_decode($table['default_product_bxdata'],true);
                    foreach($bxdata as $bxpro){ 
                        $num = $bxpro['follow']==1 && $renshu?$renshu:$bxpro['num'] ;
                        $prodata[] = $bxpro['proid'].','.$bxpro['ggid'].','.$num.',0,'.'bx_'.$bxpro['follow'];
                    }
                }
                if($table['default_product_kxdata']){
                    $kxdata = json_decode($table['default_product_kxdata'],true);
                    foreach($kxdata as $kxpro){    
                        $num = $kxpro['follow']==1 && $renshu?$renshu:$kxpro['num'] ;
                        $prodata[] = $kxpro['proid'].','.$kxpro['ggid'].','.$num.',0,'.'kx_'.$kxpro['follow'];
                    }
                }
            }
        }
        foreach($prodata as $key=>$gwc){
            list($proid,$ggid,$num,$carid) = explode(',',$gwc);
            if($carid){
                $cart = Db::name('restaurant_shop_cart')->where('aid',aid)->where('id',$carid)->select()->toArray();
                if(!$cart){
                    continue;
                }
            }
            
            $field = "id,aid,bid,cid,pic,name,sales,status_week,market_price,sell_price,lvprice,lvprice_data,freightdata,limit_per,scored_set,scored_val,status,start_time,end_time,start_hours,end_hours";
            if(getcustom('restaurant_product_jialiao')){
                $field .=',jl_is_discount';
            }
            if(getcustom('restaurant_product_package')){
                $field .=',package_is_discount,package_is_coupon,package_is_cuxiao';
            }
            if(getcustom('restaurant_product_stock_daily')){
                $field .= ",total_stock_daily_real,total_stock_daily";
            }
            if(getcustom('restaurant_weigh')|| getcustom('restaurant_product_package')){
                $field .=',product_type';
            }
            $product = Db::name('restaurant_product')->field($field)->where('aid',aid)->where('ischecked',1)->where('id',$proid)->find();
            $bid = $product['bid'];
            if(!$product){
                Db::name('restaurant_shop_cart')->where('aid',aid)->where('proid',$proid)->delete();
                return $this->json(['status'=>0,'msg'=>'产品不存在或已下架']);
            }
            $product['product_type'] = $product['product_type']??0;
            if($product['status']==0){
                return $this->json(['status'=>0,'msg'=>'菜品未上架']);
            }
            if($product['status']==2 && (strtotime($product['start_time']) > time() || strtotime($product['end_time']) < time())){
                return $this->json(['status'=>0,'msg'=>'菜品未上架']);
            }
            if($product['status']==3){
                $start_time = strtotime(date('Y-m-d '.$product['start_hours']));
                $end_time = strtotime(date('Y-m-d '.$product['end_hours']));
                if(($start_time < $end_time && ($start_time > time() || $end_time < time())) || ($start_time >= $end_time && ($start_time > time() && $end_time < time()))){
                    return $this->json(['status'=>0,'msg'=>'菜品未上架']);
                }
            }
            //周几可点
            $week = date("w");
            if($week==0) $week = 7;
            $status_week = explode(',',$product['status_week']);
            if(!in_array($week,$status_week)){
                $order_day = \app\custom\Restaurant::getStatusWeek($status_week);
                if($order_day) $order_day = '，仅限'.$order_day;
                return $this->json(['status'=>0,'msg'=>'['.$product['name'].']今日不可点'.$order_day]);
            }
            if($product['limit_per'] > 0 && $num > $product['limit_per']){ //每单限购
                return $this->json(['status'=>0,'msg'=>$product['name'].'每单限购'.$product['limit_per'].'份']);
            }
            if($product['limit_start'] > 0 && $num < $product['limit_start']){ //起售份数
                return $this->json(['status'=>0,'msg'=>$product['name'].'最低购买'.$product['limit_start'].'份']);
            }
            if($product['limit_start'] > 0){ //有起售数量
                $hasnum = Db::name('restaurant_shop_cart')->where('aid',aid)->where('mid',mid)->where('proid',$gwc['proid'])->sum('num');
                if($num > 0){ // +
                    if($hasnum + $num < $product['limit_start']) $num = $product['limit_start'] - $hasnum;
                }else{ // -
                    if($hasnum + $num < $product['limit_start']) $num = -$hasnum;
                }
            }
            if(getcustom('restaurant_table_default_product')){
                list($proid,$ggid,$num,$carid,$select_type) = explode(',',$gwc);
                if($select_type){
                    $select_type =  explode('_',$select_type);
                    $product['select_type'] =  $select_type[0]??'';
                    $product['follow'] =  $select_type[1]??0;
                }
            }
            
            $guige = Db::name('restaurant_product_guige')->where('id',$ggid)->find();
           
            $deletegg = 1;
            if(getcustom('restaurant_product_package')){
                $cartdata = Db::name('restaurant_shop_cart')->where('id',$carid) ->find();
                if($cartdata['package_data']){
                    $deletegg = 0;
                    $guige['sell_price'] = $cartdata['package_price'];
                    $package_data = json_decode($cartdata['package_data'],true);
                    $ggtext = [];
                    foreach($package_data as $pkey=>$pd){
                        $t = 'x'.$pd['num'].' '.$pd['proname'];
                        if($pd['ggname'] !='默认规格'){
                            $t .='('.$pd['ggname'].')';
                        }
                        $ggtext[] = $t;
                    }
                    $guige['ggtext'] =$ggtext;
                }
            }
            if(!$guige && $deletegg){
                Db::name('restaurant_shop_cart')->where('aid',aid)->where('ggid',$ggid)->delete();
                return $this->json(['status'=>0,'msg'=>'产品该规格不存在或已下架']);
            }
            $is_check_stock = 1;
            if(getcustom('restaurant_weigh')){
                //称重商品不校验库存
                if($product['product_type'] ==1){
                    $is_check_stock = 0;
                }
            }
            if(getcustom('restaurant_product_package')){
                if($product['product_type'] ==2){
                    $is_check_stock = 0;
                }
            }
            $is_check_daily_stock = 1;
            if(getcustom('restaurant_product_stock_daily')){
                if($product['total_stock_daily'] > 0){
                    $is_check_daily_stock = 0;
                    if($num > $product['total_stock_daily_real']){
                        return $this->json(['status'=>0,'msg'=>$product['name'].'的今日总库存不足']);
                    }
                }
            }
            if($is_check_stock){
                if($guige['stock'] < $num ){
                    return $this->json(['status'=>0,'msg'=>$product['name'].'的库存不足']);
                }
                if($guige['stock_daily'] - $guige['sales_daily']<$num && $is_check_daily_stock){
                    return $this->json(['status'=>0,'msg'=>$product['name'].'的库存不足']);
                }
            }
            if($product['limit_per'] > 0){
                if($num > $product['limit_per']){
                    return $this->json(['status'=>0,'msg'=>'每单限购'.$product['limit_per'].'件']);
                }
            }
//            $guige = $this->formatguige($guige,$product['bid'],$product['lvprice']);

            if($product['bid']>0){
                //判断商家是否能自主修改积分设置
                $business_selfscore = 0;
                if(getcustom('business_selfscore') || getcustom('business_score_jiesuan')){
                    $business_selfscore = Db::name('business_sysset')->where('aid',aid)->value('business_selfscore');
                }
                $bcansetscore = false;//商家能否修改积分
                if(getcustom('business_cansetscore')){
                    //能否修改积分
                    if($product['bid']){
                        $business_cansetscore = Db::name('business')->where('id',$product['bid'])->value('business_cansetscore');
                        $bcansetscore = $business_cansetscore && $business_cansetscore == 1?true:false;
                    }
                }
                if(!$business_selfscore && !$bcansetscore){
                    $product['scored_set'] = 0;
                }
            }
            if(!$allbuydata[$product['bid']]) $allbuydata[$product['bid']] = [];
            if(!$allbuydata[$product['bid']]['prodata']) $allbuydata[$product['bid']]['prodata'] = [];
            $jldata = ['jlprice' =>0,'jltitle' =>''];
            if(getcustom('product_jialiao')){
                
                $input_jldata =   urldecode(input('jldata'));
                if($input_jldata){
                    $jlstring = explode('-',$input_jldata);
                    $jldata['jlprice'] = $jlstring[0];
                    $jldata['jltitle'] = $jlstring[1];
                } else{
                    $cart_jldata = Db::name('restaurant_shop_cart')->field('jlprice,jltitle')->where('id',$carid) ->find();
                    if($cart_jldata)$jldata = $cart_jldata;
                }
            }      
            if(getcustom('restaurant_product_jialiao')){
                $ncart = Db::name('restaurant_shop_cart')->field('jldata')->where('id',$carid) ->find();
                if($ncart['jldata']){
                    $njldata = json_decode($ncart['jldata'],true);
                    $njlprice = 0;
                    $njltitle = '';
                    foreach($njldata as $key=>$val){
                        $njlprice += $val['num'] * $val['price'];
                        $njltitle .=$val['title'].'*'.$val['num'].'/';
                    }
                    $guige['sell_price'] = dd_money_format($guige['sell_price'] + $njlprice) ;
                    $guige['name'] = $guige['name'].'('.rtrim($njltitle,'/').')';
                }
            }
            if($bid!=0){
                $business = Db::name('business')->where('id',$bid)->field('id,aid,cid,name,logo,tel,address,sales,longitude,latitude,start_hours,end_hours,is_open')->find();
                if($business['is_open']==0) return $this->json(['status'=>-4,'msg'=>$business['name'].'未营业']);
                if($business['start_hours'] != $business['end_hours']){
                    $start_time = strtotime(date('Y-m-d '.$business['start_hours']));
                    $end_time = strtotime(date('Y-m-d '.$business['end_hours']));
                    if(($start_time < $end_time && ($start_time > time() || $end_time < time())) || ($start_time >= $end_time && ($start_time > time() && $end_time < time()))){
                        return $this->json(['status'=>0,'msg'=>'商家不在营业时间']);
                    }
                }
            }else{
                $business = Db::name('admin_set')->where('aid',aid)->field('id,name,logo,desc,tel')->find();
            }
            $prodataArr[] = $product['id'].','.$guige['id'].','.$num.','.$carid;
            $allbuydata[$product['bid']]['prodata'][] = ['product'=>$product,'guige'=>$guige,'num'=>$num,'jldata' =>$jldata,'carid' => $carid,'business' => $business];
        }
        $prodatastr = implode('-',$prodataArr);
        $allbuydata[$bid]['prodatastr'] =$prodatastr;

        $oglist = Db::name('restaurant_shop_order_goods')->where('aid',aid)->where('bid',$bid)->where('orderid',$table['orderid'])->select()->toArray();
         $new_oglist = [];
         foreach($oglist as $key=>$val){
             if(getcustom('restaurant_product_package')){
                 if($val['package_data']){
                     $package_data = json_decode($val['package_data'],true);
                     $ggtext = [];
                     foreach($package_data as $pdk=>$pd){
                         $t = 'x'.$pd['num'].' '.$pd['proname'];
                         if($pd['ggname'] !='默认规格'){
                             $t .='('.$pd['ggname'].')';
                         }
                         $ggtext[] = $t;
                     }
                     $val['ggtext'] =$ggtext;
                 }
             }
             $new_oglist[$val['bid']]['prodata'][]=  $val;
            
         }
         //必选和可选
        //下单的prodatastr
      
        $rdata['allbuydata'] = $allbuydata;
        $rdata['oglist'] = $new_oglist;
        $rdata['tableinfo'] = $table;
        return $this->json($rdata);
      
    }
    //先付后吃下单和加菜
    public function addToOrder(){
        $tableid = input('param.tableid');
        $prodata = input('param.prodata');
        $prodata = explode('-',$prodata);
        $renshu = input('param.renshu');
        if(!$tableid) return $this->json(['status'=>0,'msg'=>'请先扫描桌台二维码']);
        $tableinfo = Db::name('restaurant_table')->where('id',$tableid)->find();
        if($tableinfo['status'] ==1)return $this->json(['status'=>0,'msg'=>'桌台已被预定']);
        if($tableinfo['status'] ==3)return $this->json(['status'=>0,'msg'=>'桌台清台中']);
        $bid = $tableinfo['bid'];
        $goodsremark = input('param.remark');
        //如果有订单进行追加商品，没有订单 创建订单增加商品
        //增加order_goods
        $buydata = input('param.buydata');
        $title = '';
        $product_price = 0;
        $prolist = [];
        foreach($prodata as $key=>$gwc){
            list($proid,$ggid,$num,$carid) = explode(',',$gwc);
            if(!$num) return $this->json(['status'=>0,'msg'=>'购买数量有误']);
            $product = Db::name('restaurant_product')->where('aid',aid)->where('ischecked',1)->where('bid',$bid)->where('id',$proid)->find();
            if(!$product) return $this->json(['status'=>0,'msg'=>'产品不存在或已下架']);
            if($product['status']==0)return $this->json(['status'=>0,'msg'=>'产品未上架']);
            if($product['status']==2 && (strtotime($product['start_time']) > time() || strtotime($product['end_time']) < time()))return $this->json(['status'=>0,'msg'=>'产品未上架']);
            if($product['status']==3){
                $start_time = strtotime(date('Y-m-d '.$product['start_hours']));
                $end_time = strtotime(date('Y-m-d '.$product['end_hours']));
                if(($start_time < $end_time && ($start_time > time() || $end_time < time())) || ($start_time >= $end_time && ($start_time > time() && $end_time < time()))){
                    return $this->json(['status'=>0,'msg'=>'产品未上架']);
                }
            }
            //周几可点
            $week = date("w");
            if($week==0) $week = 7;
            $status_week = explode(',',$product['status_week']);
            if(!in_array($week,$status_week)){
                $order_day = \app\custom\Restaurant::getStatusWeek($status_week);
                if($order_day) $order_day = '，仅限'.$order_day;
                return $this->json(['status'=>0,'msg'=>'['.$product['name'].']今日不可点'.$order_day]);
            }
            if($product['limit_per'] > 0 && $num > $product['limit_per']){ //每单限购
                return $this->json(['status'=>0,'msg'=>$product['name'].'每单限购'.$product['limit_per'].'份']);
            }
            if($product['limit_start'] > 0 && $num < $product['limit_start']){ //起售份数
                return $this->json(['status'=>0,'msg'=>$product['name'].'最低购买'.$product['limit_start'].'份']);
            }
            if($key ==0)$title = $product['name'];
            $guige = Db::name('restaurant_product_guige')->where('aid',aid)->where('id',$ggid)->find();
            $deletegg = 1;
            if(getcustom('restaurant_product_package')){
                $cartdata = Db::name('restaurant_shop_cart')->where('id',$carid) ->find();
                if($cartdata['package_data']){
                    $deletegg = 0;
                    $guige['sell_price'] = $cartdata['package_price'];
                    $package_data = json_decode($cartdata['package_data'],true);
                    $ggtext = [];
                    foreach($package_data as $pdk=>$pd){
                        $t = 'x'.$pd['num'].' '.$pd['proname'];
                        if($pd['ggname'] !='默认规格'){
                            $t .='('.$pd['ggname'].')';
                        }
                        $ggtext[] = $t;
                    }
                    $guige['ggtext'] =$ggtext;
                }
            }
            if(!$guige && $deletegg){
                Db::name('restaurant_shop_cart')->where('aid',aid)->where('ggid',$ggid)->delete();
                return $this->json(['status'=>0,'msg'=>'产品该规格不存在或已下架']);
            }
            
            $is_check_stock = 1;
            if(getcustom('restaurant_weigh')){
                if($product['product_type'] ==1){
                    //称重商品不校验库存
                    $is_check_stock = 0;
                }
            }
            if(getcustom('restaurant_product_package')){
                if($product['product_type'] ==2){
                    $is_check_stock = 0;
                }
            }
            $is_check_daily_stock = 1;
            if(getcustom('restaurant_product_stock_daily')){
                if($product['total_stock_daily'] > 0){
                    $is_check_daily_stock = 0;
                    if($num > $product['total_stock_daily_real']){
                        return $this->json(['status'=>0,'msg'=>$product['name'].'的今日总库存不足']);
                    }
                }
            }
            if($is_check_stock){
                if($guige['stock'] < $num ){
                    return $this->json(['status'=>0,'msg'=>$product['name'].'库存不足']);
                }
                if($guige['stock_daily']-$guige['sales_daily'] < $num && $is_check_daily_stock){
                    return $this->json(['status'=>0,'msg'=>$product['name'].'今日库存不足']);
                }
            }
            
            $jldata = ['jlprice' =>0,'jltitle' =>''];
            if(getcustom('product_jialiao')){
                $jldata = Db::name('restaurant_shop_cart')->field('jlprice,jltitle')->where('id',$carid) ->find();
                $input_jldata =   urldecode(input('jldata'));
                if($input_jldata && !$jldata){
                    $jlstring = explode('-',$input_jldata);
                    $jldata['jlprice'] = $jlstring[0];
                    $jldata['jltitle'] = $jlstring[1];
                }
                $product_price += $jldata['jlprice'] * $num ;
            }
            if(getcustom('restaurant_product_jialiao')){
                $ncart = Db::name('restaurant_shop_cart')->field('jldata')->where('id',$carid) ->find();
                if($ncart['jldata']){
                    $njldata = json_decode($ncart['jldata'],true);
                    $njlprice = 0;
                    $njltitle = '';
                    foreach($njldata as $jk=>$val){
                        $njlprice += $val['num'] * $val['price'];
                        $njltitle .=$val['title'].'*'.$val['num'].'/';
                    }
                    $guige['sell_price'] = dd_money_format($guige['sell_price'] + $njlprice) ;
                }
            }
            $product_price +=  $guige['sell_price'] * $num;
            $remark = $goodsremark[$key];
          
            //$jldata为product_jialiao的定制
            $prolist[] = ['product'=>$product,'guige'=>$guige,'num'=>$num,'jldata' =>$jldata,'carid' => $carid??0,'remark' => $remark??''];
        }
        if($tableinfo['orderid']) {
            //存在订单
            $order = Db::name('restaurant_shop_order')->where('aid', aid)->where('id', $tableinfo['orderid'])->find();
            if($order['status'] !=0) return $this->json(['status'=>0,'msg'=>'桌台订单状态异常，请检查桌台']);
            //更新下单人
            $mids = $order['mids'];
            $ordermids = explode(',',$mids);
            if(!in_array(mid,$ordermids)){
                $ordermids[] = mid;
            }
            $ordermids =implode(',',$ordermids);
            $orderupdate = [];
            $orderupdate['mids'] = $ordermids;   
            if($order['settle_status'] ==1){
                //20250526，订单结算中，加菜时改为未结算，且返回优惠券等优惠
                $orderupdate['settle_status'] = 0;
                if($order['coupon_rid'] > 0){
                    Db::name('coupon_record')->where('aid',aid)->where(['mid'=>$order['mid'],'id'=>$order['coupon_rid']])->update(['status'=>0,'usetime'=>'']);
                }
                if($order['scoredkscore'] > 0){
                    \app\common\Member::addscore(aid,$order['mid'],$order['scoredkscore'],'订单重新结算返还');
                }
            }
            Db::name('restaurant_shop_order')->where('aid', aid)->where('id', $tableinfo['orderid'])->update($orderupdate);
            $orderid = $order['id'];
        }
        else{
            //不存在订单
            $tea_fee = 0;
            $shop_set = Db::name('restaurant_shop_sysset')->where('aid',aid)->where('bid',$bid)->find();
            $totalprice = 0;
            if($shop_set['tea_fee_status']==1){
                $tea_fee = $shop_set['tea_fee']>0 ? $shop_set['tea_fee'] * $renshu : 0;
                $totalprice = $tea_fee;
            }
            $orderdata = [
                'aid' => aid,
                'bid' => $tableinfo['bid'] ? $tableinfo['bid'] : 0,
                'mid' => 0,
                'ordernum' => date('ymdHis').rand(100000,999999),
                'renshu' => $renshu??1,
                'platform' => platform,
                'createtime' => time(),
                'tea_fee' => $tea_fee,
                'status' => 0,
                'title' =>$title.(count($prodata)>1?'等':''),
                'tableid' =>$tableid,
                'mids' => mid,//多人点餐或先吃后付的 多人mid
                'eattype' => 1,//就餐类型，0先付后吃，1先吃后付
                'totalprice' =>$totalprice
            ];
            $orderid = Db::name('restaurant_shop_order')->insertGetId($orderdata);
            $order = Db::name('restaurant_shop_order')->where('aid',aid)->where('id',$orderid)->find();
            //更新餐桌状态
            Db::name('restaurant_table')->where('aid',aid)->where('bid', $tableinfo['bid'])->where('id',$tableid)->update(['status' => 2, 'orderid' => $orderid]);
        }
       
        $lasttimes = Db::name('restaurant_shop_order_goods')->where('aid',aid)->where('bid',$order['bid'])->where('orderid',$orderid)->order('times desc')->value('times');
        if($lasttimes){
            $lasttimes=$lasttimes + 1;
        }else{
            $lasttimes= 1;
        }
        $order_totalprice = 0;
        $ogids = [];
        foreach($prolist as $key=>$pro){
            $product = $pro['product'];
            $guige = $pro['guige'];
            $num = $pro['num'];
            if(getcustom('product_jialiao')){
                $cardata = Db::name('restaurant_shop_cart')->where('aid',aid)->where('ggid',$guige['id'])->where('proid',$product['id'])->find();
                $input_jldata =   urldecode(input('jldata'));
                if( $input_jldata && !$cardata ){
                    $jlstring = explode('-',$input_jldata);
                    $cardata['jlprice'] =  $jlstring[0];
                    $cardata['jltitle'] =  $jlstring[1];
                }
            }
            if(getcustom('restaurant_product_jialiao')){
                //如果商品设置打折
                $cartid  =  $pro['carid'];//购物车
                $jldata = Db::name('restaurant_shop_cart')->where('id',$cartid)->value('jldata');
                $njlprice = 0;
                $njltitle = '';
                if($jldata){
                    $njldata = json_decode($jldata,true);
                    foreach($njldata as $key=>$val){
                        $njlprice += $val['num'] * $val['price'];
                        $njltitle .=$val['title'].'*'.$val['num'].'/';
                    }
                    $njltitle = rtrim($njltitle,'/');
                }

            }
            $ogdata = [];
            $ogdata['aid'] = aid;
            $ogdata['bid'] = $product['bid'];
            $ogdata['mid'] = mid;
            $ogdata['orderid'] = $orderid;
            $ogdata['ordernum'] = $order['ordernum'];
            $ogdata['proid'] = $product['id'];
            $ogdata['name'] = $product['name'];
            $ogdata['pic'] = $guige['pic'] ? $guige['pic'] : $product['pic'];
            $ogdata['procode'] = $product['procode'];
            $ogdata['ggid'] = $guige['id'];
            $ogdata['ggname'] = $guige['name'];
            if(getcustom('restaurant_product_package')){
                $ogdata['product_type'] = $product['product_type'];
            }
            $ogdata['num'] = $num;
            $ogdata['remark'] = $pro['remark'];
            $ogdata['cost_price'] = $guige['cost_price'];
            $sell_price =  $guige['sell_price'];
            if(getcustom('restaurant_product_package')){
                $cartdata = Db::name('restaurant_shop_cart')->where('id',$pro['carid'])->find();
                if($cartdata['package_data']){
                    $sell_price = $cartdata['package_price'];
                    $ogdata['package_data'] = $cartdata['package_data'];
                    $ogdata['is_package'] = 1;
                    $ogdata['package_price'] =$sell_price;
                }
            }
            $ogdata['sell_price'] = $sell_price;
            $ogdata['status'] = 0;
            $ogdata['createtime'] = time();
            $og_totalprice = $num * $sell_price;
            if(getcustom('product_jialiao')){
                $og_totalprice = bcadd($og_totalprice,$cardata?$cardata['jlprice']:0,2);
                $ogdata['jlprice'] = $cardata['jlprice']?$cardata['jlprice']:0;
                $ogdata['jltitle'] = $cardata['jltitle']?$cardata['jltitle']:'';
            }
            if(getcustom('restaurant_product_jialiao')){
                $ogdata['njlprice'] = $njlprice;
                $ogdata['njltitle'] = $njltitle;
            }
            $ogdata['totalprice'] =$og_totalprice;
            $ogdata['real_totalprice'] = $og_totalprice; //实际菜品销售金额
            $ogdata['times'] = $lasttimes ?? 1;
            $ogid = Db::name('restaurant_shop_order_goods')->insertGetId($ogdata);
            $ogids[] = $ogid;
            $order_totalprice +=$ogdata['totalprice'];
            //删除购物车
            Db::name('restaurant_shop_cart')->where('aid',aid)->where('id',$pro['carid'])->delete();
        }
        //重新更新
        $oupdate = [];
        $oupdate['totalprice'] = $order_totalprice + $order['totalprice'];
        $oupdate['product_price'] = $product_price + $order['product_price'];
        Db::name('restaurant_shop_order')->where('id',$orderid)->update($oupdate);
        //加菜打印
        $orderGoods = Db::name('restaurant_shop_order_goods')->alias('og')
            ->where('orderid',$orderid)->where('og.id', 'in', $ogids)->leftJoin('restaurant_product p', 'p.id=og.proid')
            ->fieldRaw('og.*,p.area_id')->select()->toArray();
        $order['isaddproduct'] = 1;
        \app\custom\Restaurant::print('restaurant_shop',$order, $orderGoods);
        $rdata = [
            'orderid' => $orderid,
            'status' => 1
        ];
        return $this->json($rdata);
    }
}